package com.yuexunit.finance.project.action.v1;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuexunit.core.BusinessException;
import com.yuexunit.core.ConfigPropertites;
import com.yuexunit.finance.bulkstock.entity.BulkstockInfoEntity;
import com.yuexunit.finance.bulkstock.service.BulkstockInfoService;
import com.yuexunit.finance.common.httpclient.HttpClientHelper;
import com.yuexunit.finance.common.util.BeanUtils;
import com.yuexunit.finance.common.util.DateUtils;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.member.entity.EnterpriseEntity;
import com.yuexunit.finance.member.service.EnterpriseService;
import com.yuexunit.finance.project.action.v1.dto.FinanceLoanCastor;
import com.yuexunit.finance.project.action.v1.model.input.PickupApplicationWarehouseInputCreateParams;
import com.yuexunit.finance.project.action.v1.model.input.PickupApplicationWarehouseInputUpdateParams;
import com.yuexunit.finance.project.action.v1.model.output.EnterpriseInvoiceInfo;
import com.yuexunit.finance.project.action.v1.model.output.FinanceFilesInfoDetail;
import com.yuexunit.finance.project.action.v1.model.output.PickupApplicationWarehouseDetail;
import com.yuexunit.finance.project.action.v1.model.output.PickupBulkstockInfo;
import com.yuexunit.finance.project.action.v1.model.output.PickupBulkstockWarehouseDetail;
import com.yuexunit.finance.project.action.v1.model.output.ResultData;
import com.yuexunit.finance.project.entity.ContainerBulkstockEntity;
import com.yuexunit.finance.project.entity.ContainerInventoryEntity;
import com.yuexunit.finance.project.entity.EnterpriseInvoiceInfoEntity;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceAuditLogEntity;
import com.yuexunit.finance.project.entity.FinanceCompleteResultEntity;
import com.yuexunit.finance.project.entity.FinanceFilesInfoEntity;
import com.yuexunit.finance.project.entity.FinanceMoneyStatementEntity;
import com.yuexunit.finance.project.entity.PickupApplicationWarehouseEntity;
import com.yuexunit.finance.project.entity.PickupBulkstockWarehouseEntity;
import com.yuexunit.finance.project.entity.lexicon.ApiFinanceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.ApiTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.FileSignStateEnum;
import com.yuexunit.finance.project.entity.lexicon.FinanceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.InvoiceTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.ProductTypeEnum;
import com.yuexunit.finance.project.entity.lexicon.WarePickupStateEnum;
import com.yuexunit.finance.project.service.ContainerBulkstockService;
import com.yuexunit.finance.project.service.ContainerInventoryService;
import com.yuexunit.finance.project.service.EnterpriseInvoiceInfoService;
import com.yuexunit.finance.project.service.FinanceApplicationService;
import com.yuexunit.finance.project.service.FinanceAuditLogService;
import com.yuexunit.finance.project.service.FinanceFilesInfoService;
import com.yuexunit.finance.project.service.FinanceMoneyStatementService;
import com.yuexunit.finance.project.service.PickupApplicationWarehouseService;
import com.yuexunit.finance.project.service.PickupBulkstockWarehouseService;
import com.yuexunit.finance.system.action.v1.dto.SendLetterMessage;
import com.yuexunit.finance.system.entity.FinanceFilesNormEntity;
import com.yuexunit.finance.system.entity.SignFileInfoEntity;
import com.yuexunit.finance.system.entity.SignFileSealInfoEntity;
import com.yuexunit.finance.system.service.FinanceFilesNormService;
import com.yuexunit.finance.system.service.SignFileInfoService;
import com.yuexunit.finance.system.service.SignFileSealInfoService;
import com.yuexunit.fs.domain.FileEntry;
import com.yuexunit.fs.service.TransferService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.jsonutil.JSON;
import com.yuexunit.page.PageCriteria;
import com.yuexunit.page.PageList;
import com.yuexunit.permission.action.PermissionActionsApi;
import com.yuexunit.permission.action.dto.RoleListDto;
import com.yuexunit.persist.PersistUtil;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.persist.hibernate.SessionRepository;
import com.yuexunit.util.DateUtil;
import com.yuexunit.util.StringUtil;

/**
 *@version 创建时间：2017年8月2日 下午2:20:06
 *@author wenwenlong
 *类说明
 */

@Implements(FinancePickupApplicationWarehouseApi.class)
public class FinancePickupApplicationWarehouseApiImpl implements FinancePickupApplicationWarehouseApi {
	private EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);

	private PickupApplicationWarehouseService pickupApplicationWarehouseService = ComponentFactory.loadClass(PickupApplicationWarehouseService.class);

	private PickupBulkstockWarehouseService pickupBulkstockWarehouseService = ComponentFactory.loadClass(PickupBulkstockWarehouseService.class);

	private EnterpriseInvoiceInfoService enterpriseInvoiceInfoService = ComponentFactory.loadClass(EnterpriseInvoiceInfoService.class);

	private FinanceFilesNormService financeFilesNormService = ComponentFactory.loadClass(FinanceFilesNormService.class);

	private FinanceFilesInfoService financeFilesInfoService = ComponentFactory.loadClass(FinanceFilesInfoService.class);

	private SignFileInfoService signFileInfoService = ComponentFactory.loadClass(SignFileInfoService.class);

	private SignFileSealInfoService signFileSealInfoService = ComponentFactory.loadClass(SignFileSealInfoService.class);

	private TransferService transferService = ComponentFactory.loadClass(TransferService.class);

	private PermissionActionsApi permissionAction = ComponentFactory.loadClass(PermissionActionsApi.class);

	private FinanceAuditLogService financeAuditLogService = ComponentFactory.loadClass(FinanceAuditLogService.class);

	private FinanceMoneyStatementService financeMoneyStatementService = ComponentFactory.loadClass(FinanceMoneyStatementService.class);

	private FinanceApplicationActionApi financeApplicationActionApi = ComponentFactory.loadClass(FinanceApplicationActionApi.class);

	private ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);

	private FinanceApplicationService financeApplicationService = ComponentFactory.loadClass(FinanceApplicationService.class);
	
	private BulkstockInfoService bulkstockInfoService = ComponentFactory.loadClass(BulkstockInfoService.class);

	private String tmp = "客户(%s)销售提货(%s)目前处于销售提货环节对应的(%s)节点，请及时审批！";

	public static Logger logger = LoggerFactory.getLogger(FinancePickupApplicationWarehouseApiImpl.class);

	@Override
	@Transactional
	public String createFinancePickupApplicationWarehouse(PickupApplicationWarehouseInputCreateParams params) {

//		Map<Long, BigDecimal> map = new HashMap<>();
//		for (int i = 0; i < params.getFinanceIds().length; i++) {
//			if (map.get(params.getFinanceIds()[i]) == null) {
//				map.put(params.getFinanceIds()[i], params.getBulkstockAmounts()[i]);
//			} else {
//				BigDecimal v = map.get(params.getFinanceIds()[i]).add(params.getBulkstockAmounts()[i]);
//				map.remove(params.getFinanceIds()[i]);
//				map.put(params.getFinanceIds()[i], v);
//			}
//		}
//
//		Iterator<Entry<Long, BigDecimal>> it = map.entrySet().iterator();
//		while (it.hasNext()) {
//			Entry<Long, BigDecimal> entry = it.next();
//			FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(entry.getKey());
//			if ((finance.getTotalLoanAmount().subtract(finance.getTotalReceivedAmount())).compareTo(entry.getValue()) < 0) {
//				throw new BusinessException("融资单号" + finance.getFinanceNumber() + ": 还款金额不能超过放款金额！");
//			}
//		}

		PickupApplicationWarehouseEntity pawe = new PickupApplicationWarehouseEntity();
		//企业信息
		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(params.getEnterpriseId());
		pawe.setEnterpriseId(enterprise.getEnterpriseId());
		pawe.setEnterpriseName(enterprise.getEnterpriseName());
		pawe.setBuyer(params.getBuyer());

		pawe.setDeliveryAddress(params.getDeliveryAddress());
		pawe.setPickupMethod(params.getPickupMethod());
		pawe.setContactMobile(params.getContactMobile());
		pawe.setContactPerson(params.getContactPerson());
		pawe.setRemark(params.getRemark());
		pawe.setInvoiceType(InvoiceTypeEnum.valueOf(params.getInvoiceType()));
		pawe.setInvoiceAccount(params.getInvoiceAccount());
		pawe.setInvoiceAddress(params.getInvoiceAddress());
		pawe.setInvoiceEnterpriseName(params.getInvoiceEnterpriseName());
		pawe.setInvoiceTaxpayerNumber(params.getInvoiceTaxpayerNumber());
		pawe.setProductType(ProductTypeEnum.valueOf(params.getProductType()));
		pawe.setFilesUuid(params.getFilesUuid());
		pawe.setCreator(FinanceSessionContext.getAccountFullName());
		pawe.setUpdator(FinanceSessionContext.getAccountFullName());
		pawe.setPickupDate(params.getPickupDate());
		pawe.setPickupState(WarePickupStateEnum.UNKNOWN);
		pawe.setCreatorId(FinanceSessionContext.getAccountId());

		pickupApplicationWarehouseService.createPickupApplicationWarehouse(pawe);

		for (int i = 0; i < params.getPickupQuantitys().length; i++) {
			if (params.getPickupQuantitys()[i].compareTo(BigDecimal.ZERO) <= 0) {
				throw new BusinessException("货物"+params.getBulkstockNames()[i]+")所提量超过监管量！");
			}

			PickupBulkstockWarehouseEntity pbwe = new PickupBulkstockWarehouseEntity();
			pbwe.setPickupId(pawe.getPickupId());

			//			StringBuffer sql = new StringBuffer();
			//			sql.append("SELECT (T1.WEIGHT - IFNULL(T2.PICKUP_QUANTITY, 0)) as WEIGHT, T1.LOCATION_ID as LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, T1.FINANCE_ID AS FINANCE_ID, T1.FINANCE_NUMBER AS FINANCE_NUMBER, T1.APPLICATION_DT AS APPLICATION_DT, T1.LOCATION_AREA AS LOCATION_AREA, T1.LOCATION_NAME AS LOCATION_NAME FROM (SELECT SUM(WEIGHT) AS WEIGHT, LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, c.PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, a.FINANCE_ID AS FINANCE_ID, a.FINANCE_NUMBER AS FINANCE_NUMBER, c.APPLICATION_DT AS APPLICATION_DT, a.LOCATION_AREA AS LOCATION_AREA, a.LOCATION_NAME AS LOCATION_NAME FROM fin_container_inventory a, fin_container_bulkstock b, fin_finance_application c WHERE a.INVENTORY_ID = b.INVENTORY_ID");
			//			sql.append(" AND a.LOCATION_ID ='").append(params.getLocationIds()[i] + "'");
			//			sql.append(" AND a.FINANCE_NUMBER ='").append(params.getFinanceNumbers()[i] + "'");
			//			sql.append(" AND a.FINANCE_ID = c.FINANCE_ID AND ((c.FINANCE_STATE IN (9,25,26,27,28,29) AND (c.SETTLEMENT_METHOD = 1 OR ISNULL(c.SETTLEMENT_METHOD))) OR (c.FINANCE_STATE IN (7, 9, 25, 26, 27, 28, 29) AND c.SETTLEMENT_METHOD = 2)) GROUP BY a.FINANCE_ID, LOCATION_ID) T1 LEFT JOIN (SELECT SUM(PICKUP_QUANTITY) AS PICKUP_QUANTITY, LOCATION_ID, FINANCE_NUMBER FROM fin_pickup_bulkstock_warehouse d, FIN_PICKUP_APPLICATION_WAREHOUSE e where d.PICKUP_ID = e.PICKUP_ID AND e.PICKUP_STATE NOT IN(1, 13) GROUP BY FINANCE_NUMBER, LOCATION_ID) T2 ON T1.LOCATION_ID = T2.LOCATION_ID AND T1.FINANCE_NUMBER = T2.FINANCE_NUMBER WHERE T1.LOCATION_ID IS NOT NULL AND T1.LOCATION_ID <> '';");
			//			Session session = SessionRepository.getCurrentSession();
			//
			//			List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("WEIGHT").addScalar("LOCATION_ID").addScalar("BULKSTOCK_NAME").addScalar("PRODUCT_TYPE").addScalar("BULKSTOCK_INFO_ID").addScalar("WAREHOUSE_NAME").addScalar("FINANCE_ID").addScalar("FINANCE_NUMBER").addScalar("LOCATION_NAME").addScalar("LOCATION_AREA").addScalar("APPLICATION_DT").addScalar("SPECIFICATION").list();
			//			for (Object l : datas) {
			//				Object[] os = (Object[])l;
			//				if (params.getPickupQuantitys()[i].compareTo((BigDecimal) os[0]) > 0) {
			//					throw new BusinessException("所提量超过监管量！");
			//				}
			//			}

			//查询监管量
			StringBuffer sql = new StringBuffer("SELECT * FROM view_fin_pickupable_bulkstock v WHERE v.ENTERPRISE_ID = ").append(pawe.getEnterpriseId());
			sql.append(" AND v.BULKSTOCK_INFO_ID = ").append(params.getBulkstockInfoIds()[i]);
			sql.append(" AND v.WAREHOUSE_ID = ").append("'"+params.getWarehouseIds()[i]+"'");
			Session session = SessionRepository.getCurrentSession();
			List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("WEIGHT").addScalar("LOCATION_ID").addScalar("BULKSTOCK_NAME").addScalar("PRODUCT_TYPE").addScalar("BULKSTOCK_INFO_ID").addScalar("WAREHOUSE_NAME").addScalar("LOCATION_NAME").addScalar("LOCATION_AREA").addScalar("SPECIFICATION").list();
			List<PickupBulkstockInfo> list = new ArrayList<>();
			for (Object l : datas) {
				Object[] os = (Object[])l;
				if (params.getPickupQuantitys()[i].compareTo((BigDecimal) os[0]) > 0) {
					throw new BusinessException("货物"+params.getBulkstockNames()[i]+")所提量超过监管量！");
				}
			}
			SessionRepository.closeCurrentSession();

			pbwe.setFinanceId(params.getFinanceIds()[i]);
			pbwe.setFinanceNumber(params.getFinanceNumbers()[i]);
			//			pbwe.setFinanceId(params.getFinanceIds()[i]);
			pbwe.setApplicationDate(DateUtil.now());
			pbwe.setProductType(ProductTypeEnum.valueOf(params.getProductType()));
			pbwe.setWarehouseName(params.getWarehouseNames()[i]);
			pbwe.setSupervisionQuantity(params.getSupervisionQuantitys()[i]);
			pbwe.setPickupQuantity(params.getPickupQuantitys()[i]);
			/*	pbwe.setPickupAmount(params.getPickupAmounts()[i]);
			pbwe.setBulkstockAmount(params.getBulkstockAmounts()[i]);
			pbwe.setInterest(params.getInterests()[i]);
			pbwe.setOthers(params.getOthers()[i]);*/
			pbwe.setBulkstockName(params.getBulkstockNames()[i]);
			pbwe.setBulkstockInfoId(params.getBulkstockInfoIds()[i]);
			pbwe.setLocationId(params.getLocationIds()[i]);
			pbwe.setWarehouseId(params.getWarehouseIds()[i]);

			pickupBulkstockWarehouseService.createPickupBulkstockWarehouse(pbwe);
		}

		if (StringUtil.isNotBlank(params.getInvoiceEnterpriseName())) {
			EnterpriseInvoiceInfoEntity eiie = enterpriseInvoiceInfoService.inquireEnterpriseInvoiceInfo(FinanceSessionContext.getAccountId() ,params.getInvoiceEnterpriseName());

			if (eiie == null) {
				eiie = new EnterpriseInvoiceInfoEntity();
				eiie.setInvoiceAccount(params.getInvoiceAccount());
				eiie.setInvoiceAddress(params.getInvoiceAddress());
				eiie.setInvoiceEnterpriseName(params.getInvoiceEnterpriseName());
				eiie.setInvoiceTaxpayerNumber(params.getInvoiceTaxpayerNumber());
				eiie.setBuyer(params.getBuyer());
				eiie.setDeliveryAddress(params.getDeliveryAddress());
				eiie.setPickupMethod(params.getPickupMethod());
				eiie.setRemark(params.getRemark());
				eiie.setContactPerson(params.getContactPerson());
				eiie.setContactMobile(params.getContactMobile());
				eiie.setAccountId(FinanceSessionContext.getAccountId());

				enterpriseInvoiceInfoService.createEnterpriseInvoiceInfo(eiie);
			} else {
				eiie.setInvoiceAccount(params.getInvoiceAccount());
				eiie.setInvoiceAddress(params.getInvoiceAddress());
				eiie.setInvoiceTaxpayerNumber(params.getInvoiceTaxpayerNumber());
				eiie.setBuyer(params.getBuyer());
				eiie.setDeliveryAddress(params.getDeliveryAddress());
				eiie.setPickupMethod(params.getPickupMethod());
				eiie.setRemark(params.getRemark());
				eiie.setContactPerson(params.getContactPerson());
				eiie.setContactMobile(params.getContactMobile());
				eiie.setAccountId(FinanceSessionContext.getAccountId());

				enterpriseInvoiceInfoService.updateEnterpriseInvoiceInfo(eiie);
			}
		}

		return pawe.getPickupId().toString();
	}

	@Override
	@Transactional
	public void updateFinancePickupApplicationWarehouse(PickupApplicationWarehouseInputUpdateParams params) {
		Map<Long, BigDecimal> map = new HashMap<>();
		for (int i = 0; i < params.getFinanceIds().length; i++) {
			if (map.get(params.getFinanceIds()[i]) == null) {
				map.put(params.getFinanceIds()[i], params.getBulkstockAmounts()[i]);
			} else {
				BigDecimal v = map.get(params.getFinanceIds()[i]).add(params.getBulkstockAmounts()[i]);
				map.remove(params.getFinanceIds()[i]);
				map.put(params.getFinanceIds()[i], v);
			}
		}

		Iterator<Entry<Long, BigDecimal>> it = map.entrySet().iterator();
		while (it.hasNext()) {
			Entry<Long, BigDecimal> entry = it.next();
			FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(entry.getKey());
			if ((finance.getTotalLoanAmount().subtract(finance.getTotalReceivedAmount())).compareTo(entry.getValue()) < 0) {
				throw new BusinessException("融资单号" + finance.getFinanceNumber() + ": 还款金额不能超过未还金额！");
			}
		}
		
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(params.getPickupId());
		if (pawe.getPickupState() != WarePickupStateEnum.UNKNOWN) {
			throw new BusinessException("只有待提交的提货才可修改！");
		}
		//企业信息
		EnterpriseEntity enterprise = enterpriseService.inquireEnterprise(params.getEnterpriseId());
		pawe.setEnterpriseId(enterprise.getEnterpriseId());
		pawe.setEnterpriseName(enterprise.getEnterpriseName());
		pawe.setBuyer(params.getBuyer());

		pawe.setDeliveryAddress(params.getDeliveryAddress());
		pawe.setPickupMethod(params.getPickupMethod());
		pawe.setContactMobile(params.getContactMobile());
		pawe.setContactPerson(params.getContactPerson());
		pawe.setRemark(params.getRemark());
		pawe.setInvoiceType(InvoiceTypeEnum.valueOf(params.getInvoiceType()));
		pawe.setInvoiceAccount(params.getInvoiceAccount());
		pawe.setInvoiceAddress(params.getInvoiceAddress());
		pawe.setInvoiceEnterpriseName(params.getInvoiceEnterpriseName());
		pawe.setInvoiceTaxpayerNumber(params.getInvoiceTaxpayerNumber());
		pawe.setProductType(ProductTypeEnum.valueOf(params.getProductType()));
		pawe.setFilesUuid(params.getFilesUuid());
		pawe.setPickupDate(params.getPickupDate());
		pawe.setPickupId(params.getPickupId());
		pawe.setPickupNumber(params.getPickupNumber());
		pawe.setPickupState(WarePickupStateEnum.valueOf(params.getPickupState()));
		pawe.setUpdator(FinanceSessionContext.getAccountFullName());

		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		//删除提货货物
		List<PickupBulkstockWarehouseEntity> pickupBulkstockWarehouseList = pickupBulkstockWarehouseService.inquirePickupBulkstockWarehouseList(params.getPickupId(), null);
		if(pickupBulkstockWarehouseList != null && pickupBulkstockWarehouseList.size() > 0) {
			for (PickupBulkstockWarehouseEntity pickupBulkstockWarehouseEntity : pickupBulkstockWarehouseList) {
				//				weight = weight.add(pickupBulkstockWarehouseEntity.getPickupQuantity());
				pickupBulkstockWarehouseService.deletePickupBulkstockWarehouse(pickupBulkstockWarehouseEntity.getPickupBulkstockId());
			}
		}

		for (int i = 0; i < params.getPickupQuantitys().length; i++) {
			//			PickupBulkstockWarehouseEntity pbwe = new PickupBulkstockWarehouseEntity();
			//			pbwe.setPickupId(pawe.getPickupId());
			//
			//			StringBuffer sql = new StringBuffer();
			//			sql.append("SELECT (T1.WEIGHT - IFNULL(T2.PICKUP_QUANTITY, 0)) as WEIGHT, T1.LOCATION_ID as LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, T1.FINANCE_ID AS FINANCE_ID, T1.FINANCE_NUMBER AS FINANCE_NUMBER, T1.APPLICATION_DT AS APPLICATION_DT, T1.LOCATION_AREA AS LOCATION_AREA, T1.LOCATION_NAME AS LOCATION_NAME FROM (SELECT SUM(WEIGHT) AS WEIGHT, LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, c.PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, a.FINANCE_ID AS FINANCE_ID, a.FINANCE_NUMBER AS FINANCE_NUMBER, c.APPLICATION_DT AS APPLICATION_DT, a.LOCATION_AREA AS LOCATION_AREA, a.LOCATION_NAME AS LOCATION_NAME FROM fin_container_inventory a, fin_container_bulkstock b, fin_finance_application c WHERE a.INVENTORY_ID = b.INVENTORY_ID");
			//			sql.append(" AND a.LOCATION_ID ='").append(params.getLocationIds()[i] + "'");
			//			sql.append(" AND a.FINANCE_NUMBER ='").append(params.getFinanceNumbers()[i] + "'");
			//			sql.append(" AND a.FINANCE_ID = c.FINANCE_ID AND ((c.FINANCE_STATE IN (9,25,26,27,28,29) AND (c.SETTLEMENT_METHOD = 1 OR ISNULL(c.SETTLEMENT_METHOD))) OR (c.FINANCE_STATE IN (7, 9, 25, 26, 27, 28, 29) AND c.SETTLEMENT_METHOD = 2)) GROUP BY a.FINANCE_ID, LOCATION_ID) T1 LEFT JOIN (SELECT SUM(PICKUP_QUANTITY) AS PICKUP_QUANTITY, LOCATION_ID, FINANCE_NUMBER FROM fin_pickup_bulkstock_warehouse d, FIN_PICKUP_APPLICATION_WAREHOUSE e where d.PICKUP_ID = e.PICKUP_ID AND e.PICKUP_STATE NOT IN(1, 13) GROUP BY FINANCE_NUMBER, LOCATION_ID) T2 ON T1.LOCATION_ID = T2.LOCATION_ID AND T1.FINANCE_NUMBER = T2.FINANCE_NUMBER WHERE T1.LOCATION_ID IS NOT NULL AND T1.LOCATION_ID <> '';");
			//			Session session = SessionRepository.getCurrentSession();
			//
			//			List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("WEIGHT").addScalar("LOCATION_ID").addScalar("BULKSTOCK_NAME").addScalar("PRODUCT_TYPE").addScalar("BULKSTOCK_INFO_ID").addScalar("WAREHOUSE_NAME").addScalar("FINANCE_ID").addScalar("FINANCE_NUMBER").addScalar("LOCATION_NAME").addScalar("LOCATION_AREA").addScalar("APPLICATION_DT").addScalar("SPECIFICATION").list();
			//			for (Object l : datas) {
			//				Object[] os = (Object[])l;
			//				if (params.getPickupQuantitys()[i].compareTo(((BigDecimal) os[0]).add(weight)) > 0) {
			//					throw new BusinessException("所提量超过监管量！");
			//				}
			//			}
			//
			//			pbwe.setFinanceNumber(params.getFinanceNumbers()[i]);
			//			pbwe.setFinanceId(params.getFinanceIds()[i]);
			//			pbwe.setApplicationDate(DateUtil.now());
			//			pbwe.setProductType(ProductTypeEnum.valueOf(params.getProductType()));
			//			pbwe.setWarehouseName(params.getWarehouseNames()[i]);
			//			pbwe.setSupervisionQuantity(params.getSupervisionQuantitys()[i]);
			//			pbwe.setPickupQuantity(params.getPickupQuantitys()[i]);
			//			pbwe.setPickupAmount(params.getPickupAmounts()[i]);
			//			pbwe.setBulkstockAmount(params.getBulkstockAmounts()[i]);
			//			pbwe.setInterest(params.getInterests()[i]);
			//			pbwe.setOthers(params.getOthers()[i]);
			//			pbwe.setBulkstockName(params.getBulkstockNames()[i]);
			//			pbwe.setBulkstockInfoId(params.getBulkstockInfoIds()[i]);
			//			pbwe.setLocationId(params.getLocationIds()[i]);
			//
			//			pickupBulkstockWarehouseService.createPickupBulkstockWarehouse(pbwe);
			//			SessionRepository.closeCurrentSession();

			PickupBulkstockWarehouseEntity pbwe = new PickupBulkstockWarehouseEntity();
			pbwe.setPickupId(pawe.getPickupId());

			pbwe.setFinanceId(params.getFinanceIds()[i]);
			pbwe.setFinanceNumber(params.getFinanceNumbers()[i]);
			pbwe.setApplicationDate(DateUtil.now());
			pbwe.setProductType(ProductTypeEnum.valueOf(params.getProductType()));
			pbwe.setWarehouseName(params.getWarehouseNames()[i]);
			pbwe.setSupervisionQuantity(params.getSupervisionQuantitys()[i]);
			pbwe.setPickupQuantity(params.getPickupQuantitys()[i]);
			pbwe.setPickupQuantity(params.getPickupQuantitys()[i]);
			pbwe.setPickupAmount(params.getPickupAmounts()[i]);
			pbwe.setBulkstockAmount(params.getBulkstockAmounts()[i]);
			pbwe.setInterest(params.getInterests()[i]);
			pbwe.setOthers(params.getOthers()[i]);
			pbwe.setBulkstockName(params.getBulkstockNames()[i]);
			pbwe.setBulkstockInfoId(params.getBulkstockInfoIds()[i]);
			pbwe.setLocationId(params.getLocationIds()[i]);
			pbwe.setWarehouseId(params.getWarehouseIds()[i]);

			pickupBulkstockWarehouseService.createPickupBulkstockWarehouse(pbwe);
		}

		if (StringUtil.isNotBlank(params.getInvoiceEnterpriseName())) {
			EnterpriseInvoiceInfoEntity eiie = enterpriseInvoiceInfoService.inquireEnterpriseInvoiceInfo(FinanceSessionContext.getAccountId(), params.getInvoiceEnterpriseName());
			if (eiie == null) {
				eiie = new EnterpriseInvoiceInfoEntity();
				eiie.setInvoiceAccount(params.getInvoiceAccount());
				eiie.setInvoiceAddress(params.getInvoiceAddress());
				eiie.setInvoiceEnterpriseName(params.getInvoiceEnterpriseName());
				eiie.setInvoiceTaxpayerNumber(params.getInvoiceTaxpayerNumber());
				enterpriseInvoiceInfoService.updateEnterpriseInvoiceInfo(eiie);
			} else {
				eiie.setInvoiceAccount(params.getInvoiceAccount());
				eiie.setInvoiceAddress(params.getInvoiceAddress());
				eiie.setInvoiceTaxpayerNumber(params.getInvoiceTaxpayerNumber());
				enterpriseInvoiceInfoService.updateEnterpriseInvoiceInfo(eiie);
			}
		}

	}

	@Override
	@Transactional
	public void submitFinancePickupApplicationWarehouse(Long pickupId) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		if (pawe.getPickupState() != WarePickupStateEnum.UNKNOWN) {
			throw new BusinessException("不可重复提交");
		}
		pawe.setPickupState(WarePickupStateEnum.FIRST_APPROVE);
		pawe.setFinalId(ApiFinanceStateEnum.SW.getCode());
		pawe.setFinalNode(ApiFinanceStateEnum.SW.getView());
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		List<PickupBulkstockWarehouseEntity> pbwes = pickupBulkstockWarehouseService.inquirePickupBulkstockWarehouseList(pickupId, null);
		for (PickupBulkstockWarehouseEntity pbwe : pbwes) {
			FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(pbwe.getFinanceId());
			//			finance.setFinanceState(FinanceStateEnum.PICKUP_APPROVE_WAREHOUSE);
			financeApplicationService.updateFinanceApplication(finance);
		}

		//消息推送-商务部
		SendLetterMessage.sendLetterMessage("warehouseAudit1_1", String.format(tmp, pawe.getEnterpriseName(), pawe.getPickupNumber(), "商务部审核"));
	}

	@Override
	@Transactional
	public void cancelFinancePickupApplicationWarehouse(Long pickupId) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		pawe.setFinalId(null);
		pawe.setFinalNode("");
		pawe.setPickupState(WarePickupStateEnum.CANCEL);
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		List<PickupBulkstockWarehouseEntity> pbwes = pickupBulkstockWarehouseService.inquirePickupBulkstockWarehouseList(pickupId, null);
		for (PickupBulkstockWarehouseEntity pbwe : pbwes) {
			FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(pbwe.getFinanceId());
			//			finance.setFinanceState(FinanceStateEnum.PICKUP_APPROVE_WAREHOUSE_CANCEL);
			financeApplicationService.updateFinanceApplication(finance);
		}
	}

	@Override
	@Transactional
	public void finishPickupApplicationWarehouseClientSign(Long pickupId) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		pawe.setPickupState(WarePickupStateEnum.WAIT_CONFIRM);
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
	}

	@Override
	@Transactional
	public void confirmWarehousePickupContract(Long pickupId, String fileUuid) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);

		SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(fileUuid);
		sfie.setFileSignState(FileSignStateEnum.CONFIRM);
		signFileInfoService.updateSignFileInfo(sfie);

		PickupApplicationWarehouseDetail pawd = inquireFinancePickupApplicationWarehouse(pickupId);
		Boolean flag = Boolean.TRUE;
		outer : for (FinanceFilesInfoDetail ffid : pawd.getFinanceFilesInfoList()) {
			for (String str : ffid.getFileSignState().split(",")) {
				if (!"6".equals(str)) {
					flag = Boolean.FALSE;
					break outer;
				}
			}
		}

		if (Boolean.TRUE == flag) {
			pawe.setPickupState(WarePickupStateEnum.SECOND_APPROVE);
			pawe.setFinalId(ApiFinanceStateEnum.FK.getCode());
			pawe.setFinalNode(ApiFinanceStateEnum.FK.getView());

			pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
			//消息推送-风控
			SendLetterMessage.sendLetterMessage("warehouseAudit4_1", String.format(tmp, pawe.getEnterpriseName(), pawe.getPickupNumber(), "风控部"));
		}
	}

	@Override
	@Transactional
	public void confirmWarehousePickupContractAll(Long pickupId) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);

		List<FinanceFilesInfoEntity> ffies = financeFilesInfoService.inquireFinanceFilesInfoListByPickupId(pickupId);
		for (FinanceFilesInfoEntity ffie : ffies) {
			for (String s : ffie.getFilesUuid().split(",")) {
				SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(s);
				if (sfie == null || sfie.getFileSignState() == FileSignStateEnum.CALLBACK_PLATFORM) {
					continue;
				} else {
					sfie.setFileSignState(FileSignStateEnum.CONFIRM);
					signFileInfoService.updateSignFileInfo(sfie);
				}
			}
		}

		PickupApplicationWarehouseDetail pawd = inquireFinancePickupApplicationWarehouse(pickupId);
		Boolean flag = Boolean.TRUE;
		outer : for (FinanceFilesInfoDetail ffid : pawd.getFinanceFilesInfoList()) {
			for (String str : ffid.getFileSignState().split(",")) {
				if (!"6".equals(str)) {
					flag = Boolean.FALSE;
					break outer;
				}
			}
		}

		if (Boolean.TRUE == flag) {
			pawe.setPickupState(WarePickupStateEnum.SECOND_APPROVE);
			pawe.setFinalId(ApiFinanceStateEnum.FK.getCode());
			pawe.setFinalNode(ApiFinanceStateEnum.FK.getView());

			pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
			//消息推送-风控
			SendLetterMessage.sendLetterMessage("warehouseAudit4_1", String.format(tmp, pawe.getEnterpriseName(), pawe.getPickupNumber(), "风控部"));
		}
	}

	@Override
	public PickupApplicationWarehouseDetail inquireFinancePickupApplicationWarehouse(Long pickupId) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		PickupApplicationWarehouseDetail pawd = new PickupApplicationWarehouseDetail();
		BeanUtils.copyProperties(pawe, pawd);
		pawd.setInvoiceType(pawe.getInvoiceType().ordinal());
		pawd.setProductType(pawe.getProductType().ordinal());
		pawd.setPickupState(pawe.getPickupState().ordinal());
		pawd.setPickupStateView(pawe.getPickupState().getValue());

		List<FinanceFilesInfoEntity> ffies = financeFilesInfoService.inquireFinanceFilesInfoListByPickupId(pickupId);
		List<FinanceFilesInfoDetail> ffids = new ArrayList<>();
		List<FinanceFilesInfoDetail> ffids1 = new ArrayList<>();
		for (FinanceFilesInfoEntity ffie : ffies) {
			FinanceFilesInfoDetail ffid = new FinanceFilesInfoDetail();
			BeanUtils.copyProperties(ffie, ffid);
			StringBuffer sb = new StringBuffer();
			StringBuffer sb1 = new StringBuffer();
			StringBuffer sb2 = new StringBuffer();
			for (String s : ffie.getFilesUuid().split(",")) {
				SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(s);
				if (sfie == null) {
					continue;
				}
				sb2.append(sfie.getFilesSign() + ",");
				sb1.append(sfie.getMsg() + ",");
				sb.append(sfie.getFileSignState().ordinal() + ",");

				FinanceFilesInfoDetail ffid1 = new FinanceFilesInfoDetail();
				FileEntry fe1 = transferService.inquireFileEntry(s);
				ffid1.setFilesUuid(s);
				ffid1.setNormFileName(ffie.getNormFileName());
				ffid1.setFileSignState(sfie.getFileSignState().ordinal() + "");
				ffid1.setMsg(sfie.getMsg() + "");
				ffid1.setFileSignState(sfie.getFilesSign() + "");
				ffid1.setBasePath(ConfigPropertites.getProperties("UPLOAD_FILE"));
				ffid1.setFileName(fe1.getFileName());
				ffid1.setFileCreateTime(fe1.getCreateTime());
				ffids1.add(ffid1);
			}
			if (sb != null && sb.length() > 0) {
				sb = sb.deleteCharAt(sb.length() - 1);
				sb1 = sb1.deleteCharAt(sb1.length() - 1);
				sb2 = sb2.deleteCharAt(sb2.length() - 1);
			}
			ffid.setFileSignState(sb.toString());
			ffid.setMsg(sb1.toString());
			ffid.setIsSign(sb2.toString());
			ffids.add(ffid);
		}
		pawd.setFinanceFilesInfoList(ffids);
		pawd.setFinanceFilesInfoList1(ffids1);

		pawd.setSubmissionStatus(pawe.getSubmissionStatus());
		pawd.setSubmissionStatus2(pawe.getSubmissionStatus2());
		pawd.setSubmissionStatus3(pawe.getSubmissionStatus3());
		pawd.setSubmissionStatus4(pawe.getSubmissionStatus4());
		pawd.setSubmissionStatus5(pawe.getSubmissionStatus5());
		pawd.setSubmissionStatus6(pawe.getSubmissionStatus6());
		pawd.setSubmissionStatus7(pawe.getSubmissionStatus7());
		pawd.setSubmissionStatus8(pawe.getSubmissionStatus8());
		pawd.setSubmissionStatus9(pawe.getSubmissionStatus9());		
		pawd.setFilesUuid6(pawe.getFilesUuid6());

		BigDecimal pickupAmounts = BigDecimal.ZERO;
		BigDecimal pickupQuantitys = BigDecimal.ZERO;
		BigDecimal supervisionQuantitys = BigDecimal.ZERO;

		//提货货物信息
		List<PickupBulkstockWarehouseEntity> pbwes = pickupBulkstockWarehouseService.inquirePickupBulkstockWarehouseList(pickupId, null);
		for (PickupBulkstockWarehouseEntity pbwe : pbwes) {
			//			PickupBulkstockWarehouseDetail pbwd = new PickupBulkstockWarehouseDetail();
			//			BeanUtils.copyProperties(pbwe, pbwd);
			//			pbwd.setProductType(pbwe.getProductType().ordinal());
			//
			//			StringBuffer sql = new StringBuffer();
			//			sql.append("SELECT (T1.WEIGHT - IFNULL(T2.PICKUP_QUANTITY, 0)) as WEIGHT, T1.LOCATION_ID as LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, T1.FINANCE_ID AS FINANCE_ID, T1.FINANCE_NUMBER AS FINANCE_NUMBER, T1.APPLICATION_DT AS APPLICATION_DT, T1.LOCATION_AREA AS LOCATION_AREA, T1.LOCATION_NAME AS LOCATION_NAME FROM (SELECT SUM(WEIGHT) AS WEIGHT, LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, c.PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, a.FINANCE_ID AS FINANCE_ID, a.FINANCE_NUMBER AS FINANCE_NUMBER, c.APPLICATION_DT AS APPLICATION_DT, a.LOCATION_AREA AS LOCATION_AREA, a.LOCATION_NAME AS LOCATION_NAME FROM fin_container_inventory a, fin_container_bulkstock b, fin_finance_application c WHERE a.INVENTORY_ID = b.INVENTORY_ID");
			//			sql.append(" AND a.LOCATION_ID ='").append(pbwe.getLocationId() + "'");
			//			sql.append(" AND a.FINANCE_NUMBER ='").append(pbwe.getFinanceNumber() + "'");
			//			sql.append(" AND a.FINANCE_ID = c.FINANCE_ID AND ((c.FINANCE_STATE IN (9,25,26,27,28,29) AND (c.SETTLEMENT_METHOD = 1 OR ISNULL(c.SETTLEMENT_METHOD))) OR (c.FINANCE_STATE IN (7, 9, 25, 26, 27, 28, 29) AND c.SETTLEMENT_METHOD = 2)) GROUP BY a.FINANCE_ID, LOCATION_ID) T1 LEFT JOIN (SELECT SUM(PICKUP_QUANTITY) AS PICKUP_QUANTITY, LOCATION_ID, FINANCE_NUMBER FROM fin_pickup_bulkstock_warehouse d, FIN_PICKUP_APPLICATION_WAREHOUSE e where d.PICKUP_ID = e.PICKUP_ID AND e.PICKUP_STATE NOT IN(1, 13) GROUP BY FINANCE_NUMBER, LOCATION_ID) T2 ON T1.LOCATION_ID = T2.LOCATION_ID AND T1.FINANCE_NUMBER = T2.FINANCE_NUMBER WHERE T1.LOCATION_ID IS NOT NULL AND T1.LOCATION_ID <> '';");
			//			Session session = SessionRepository.getCurrentSession();
			//			List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("WEIGHT").addScalar("LOCATION_ID").addScalar("BULKSTOCK_NAME").addScalar("PRODUCT_TYPE").addScalar("BULKSTOCK_INFO_ID").addScalar("WAREHOUSE_NAME").addScalar("FINANCE_ID").addScalar("FINANCE_NUMBER").addScalar("LOCATION_NAME").addScalar("LOCATION_AREA").addScalar("APPLICATION_DT").addScalar("SPECIFICATION").list();
			//			for (Object l : datas) {
			//				Object[] os = (Object[])l;
			//				pbwd.setSupervisionQuantity((BigDecimal) os[0]);
			//				pbwd.setLocationName((String) os[8]);
			//				pbwd.setLocationArea((String) os[9]);
			//				pbwd.setFinanceApplicationDate((Date) os[10]);
			//				pbwd.setSpecifician((String) os[11]);
			//				pbwd.setApplicationDate((Date) os[10]);
			//			}
			//
			//			pickupAmounts = pickupAmounts.add(pbwd.getPickupAmount());
			//			pickupQuantitys = pickupQuantitys.add(pbwd.getPickupQuantity());
			//			supervisionQuantitys = supervisionQuantitys.add(pbwd.getSupervisionQuantity());
			//
			//			pawd.getBulkstockList().add(pbwd);
			//			SessionRepository.closeCurrentSession();

			PickupBulkstockWarehouseDetail pbwd = new PickupBulkstockWarehouseDetail();
			BeanUtils.copyProperties(pbwe, pbwd);
			pbwd.setProductType(pbwe.getProductType().ordinal());

			ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
			ContainerBulkstockService containerBulkstockService = ComponentFactory.loadClass(ContainerBulkstockService.class);
			List<ContainerInventoryEntity> cies = containerInventoryService.inquireContainerInventoryListByLocationId(pbwd.getLocationId());
			if (cies != null && cies.size() > 0) {
				pbwd.setLocationName(cies.get(0).getLocationName());
				pbwd.setLocationArea(cies.get(0).getLocationArea());
				List<ContainerBulkstockEntity> cbes = containerBulkstockService.inquireContainerBulkstockList(cies.get(0).getInventoryId());
				if (cbes != null && cbes.size() > 0) {
					pbwd.setSpecifician(cbes.get(0).getSpecification());
				}
			}

			//查询监管量
			StringBuffer sql = new StringBuffer("SELECT * FROM view_fin_pickupable_bulkstock v WHERE v.ENTERPRISE_ID = ").append(pawe.getEnterpriseId());
			sql.append(" AND v.BULKSTOCK_INFO_ID = ").append(pbwe.getBulkstockInfoId());
			sql.append(" AND v.WAREHOUSE_ID = ").append("'"+pbwe.getWarehouseId()+"'");
			Session session = SessionRepository.getCurrentSession();
			List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("WEIGHT").addScalar("LOCATION_ID").addScalar("BULKSTOCK_NAME").addScalar("PRODUCT_TYPE").addScalar("BULKSTOCK_INFO_ID").addScalar("WAREHOUSE_NAME").addScalar("LOCATION_NAME").addScalar("LOCATION_AREA").addScalar("SPECIFICATION").list();
			List<PickupBulkstockInfo> list = new ArrayList<>();
			for (Object l : datas) {
				Object[] os = (Object[])l;
				if (BigDecimal.ZERO.compareTo((BigDecimal) os[0]) >= 0) {
					continue;
				}
				pbwd.setSupervisionQuantity((BigDecimal) os[0]);
			}
			SessionRepository.closeCurrentSession();

			pawd.getBulkstockList().add(pbwd);
		}
		pawd.setPickupAmounts(pickupAmounts);
		pawd.setPickupQuantitys(pickupQuantitys);
		pawd.setSupervisionQuantitys(supervisionQuantitys);
		return pawd;
	}

	@Override
	@Transactional
	public void deregulationPickupApplicationWarehouse(Long pickupId) {
		PickupApplicationWarehouseDetail pawd = inquireFinancePickupApplicationWarehouse(pickupId);
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);

		ResultData result = null;
		if ("1".equals(pawe.getOutplanFlag())) {
			List<String> location_id = new ArrayList<>();
			List<BigDecimal> quantitys = new ArrayList<>();
			List<BigDecimal> weights = new ArrayList<>();
			List<BigDecimal> volumes = new ArrayList<>();
			List<String> locationNames = new ArrayList<>();
			List<String> locationAreas = new ArrayList<>();
			List<Long> goods_id = new ArrayList<>();
			List<String> financeNumber = new ArrayList<>();
			List<String> warehouseId = new ArrayList<>();
			for (PickupBulkstockWarehouseDetail pbwd : pawd.getBulkstockList()) {
				location_id.add(pbwd.getLocationId());
				goods_id.add(pbwd.getBulkstockInfoId());
				quantitys.add(new BigDecimal(1));
				weights.add(pbwd.getPickupQuantity());
				volumes.add(new BigDecimal(0));
				locationNames.add(pbwd.getLocationName());
				locationAreas.add(pbwd.getLocationArea());
				financeNumber.add(pbwd.getFinanceNumber());
				warehouseId.add(pbwd.getWarehouseId());
			}
			result = financeApplicationActionApi.getOutboundPlan(pawd.getPickupNumber(), pawd.getProductType(), pawd.getEnterpriseId().toString(), financeNumber.toArray(new String[financeNumber.size()]), location_id.toArray(new String[location_id.size()]), goods_id.toArray(new Long[goods_id.size()]), quantitys.toArray(new BigDecimal[quantitys.size()]), weights.toArray(new BigDecimal[weights.size()]), volumes.toArray(new BigDecimal[volumes.size()]), locationNames.toArray(new String[locationNames.size()]), locationAreas.toArray(new String[locationAreas.size()]), warehouseId.toArray(new String[warehouseId.size()]));
		}

//		if (result != null && "success".equals(result.getStatus())) {
		pawe.setOutplanFlag("0");
//		}

		for (PickupBulkstockWarehouseDetail pbwd : pawd.getBulkstockList()) {
			FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(pbwd.getFinanceId());
			finance.setFinanceState(FinanceStateEnum.PICKUP_APPROVE_WAREHOUSE_FINISHED);
			financeApplicationService.updateFinanceApplication(finance);

			//			StringBuffer sql = new StringBuffer();
			//			sql.append("SELECT (T1.WEIGHT - IFNULL(T2.PICKUP_QUANTITY, 0)) as WEIGHT, T1.LOCATION_ID as LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, T1.FINANCE_ID AS FINANCE_ID, T1.FINANCE_NUMBER AS FINANCE_NUMBER, T1.APPLICATION_DT AS APPLICATION_DT, T1.LOCATION_AREA AS LOCATION_AREA, T1.LOCATION_NAME AS LOCATION_NAME FROM (SELECT SUM(WEIGHT) AS WEIGHT, LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, c.PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, a.FINANCE_ID AS FINANCE_ID, a.FINANCE_NUMBER AS FINANCE_NUMBER, c.APPLICATION_DT AS APPLICATION_DT, a.LOCATION_AREA AS LOCATION_AREA, a.LOCATION_NAME AS LOCATION_NAME FROM fin_container_inventory a, fin_container_bulkstock b, fin_finance_application c WHERE a.INVENTORY_ID = b.INVENTORY_ID");
			//			sql.append(" AND a.FINANCE_NUMBER ='").append(pbwd.getFinanceNumber() + "'");
			//			sql.append(" AND a.FINANCE_ID = c.FINANCE_ID AND ((c.FINANCE_STATE IN (9,25,26,27,28,29) AND (c.SETTLEMENT_METHOD = 1 OR ISNULL(c.SETTLEMENT_METHOD))) OR (c.FINANCE_STATE IN (7, 9, 25, 26, 27, 28, 29) AND c.SETTLEMENT_METHOD = 2)) GROUP BY a.FINANCE_ID) T1 LEFT JOIN (SELECT SUM(PICKUP_QUANTITY) AS PICKUP_QUANTITY, LOCATION_ID, FINANCE_NUMBER FROM fin_pickup_bulkstock_warehouse d, FIN_PICKUP_APPLICATION_WAREHOUSE e where d.PICKUP_ID = e.PICKUP_ID AND e.PICKUP_STATE IN(11, 12) GROUP BY FINANCE_NUMBER, LOCATION_ID) T2 ON T1.LOCATION_ID = T2.LOCATION_ID AND T1.FINANCE_NUMBER = T2.FINANCE_NUMBER WHERE T1.LOCATION_ID IS NOT NULL AND T1.LOCATION_ID <> '';");
			//			Session session = SessionRepository.getCurrentSession();
			//
			//			List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("WEIGHT").addScalar("LOCATION_ID").addScalar("BULKSTOCK_NAME").addScalar("PRODUCT_TYPE").addScalar("BULKSTOCK_INFO_ID").addScalar("WAREHOUSE_NAME").addScalar("FINANCE_ID").addScalar("FINANCE_NUMBER").addScalar("LOCATION_NAME").addScalar("LOCATION_AREA").addScalar("APPLICATION_DT").addScalar("SPECIFICATION").list();
			//			for (Object l : datas) {
			//				Object[] os = (Object[])l;
			//				FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(pbwd.getFinanceId());
			//				if (((BigDecimal) os[0]).compareTo(BigDecimal.ZERO) <= 0) {
			////					List<ContainerInventoryEntity> cies = containerInventoryService.inquireContainerInventoryList(pbwd.getFinanceId(), null);
			////					for (ContainerInventoryEntity cie : cies) {
			////						financeApplicationActionApi.completeOutbound(cie.getCaseNumber());
			////					}
			//					finance.setFinanceState(FinanceStateEnum.PICKUP_APPROVE_WAREHOUSE_FINISHED);
			//					financeApplicationService.updateFinanceApplication(finance);
			//				}
			//			}
			//			SessionRepository.closeCurrentSession();
		}
//		pawe.setPickupState(WarePickupStateEnum.RELEASED);
		pawe.setFinalNode("解除监管已完成");
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
	}

	@Override
	public PageList<PickupApplicationWarehouseDetail> inquireFinancePickupApplicationWarehousePageList(
			Integer[] pickupState, String pickupNumber, String creator, Date screatDt, Date ecreatDt, Long enterpriseId,
			String buyer, Date spickupDt, Date epickupDt, String financeNumber, Integer productType, Boolean isProvider,
			String bulkstockName, Long financeId, String warehouseName, PageCriteria page) {
		Long creatorId = null;
		
		List<WarePickupStateEnum> pickupStates = null;
		if (pickupState != null && pickupState.length > 0) {
			pickupStates = new ArrayList<>();
			for (int i = 0; i < pickupState.length; i++) {
				if (pickupState[i] != null) {
					pickupStates.add(WarePickupStateEnum.valueOf(pickupState[i]));
				}
			}
		}

		List<Long> pickupIds = null;
		if (StringUtil.isNotBlank(financeNumber) || productType != null || StringUtil.isNotBlank(bulkstockName) || StringUtil.isNotBlank(warehouseName) || financeId != null) {
			pickupIds = pickupBulkstockWarehouseService.getPickupIds(financeNumber, productType, bulkstockName, financeId, warehouseName);
		}
		if (pickupIds != null && pickupIds.size() == 0) {
			return new PageList<>(page);
		}
		String buyer1=null;
		if(financeId == null){
			if (Boolean.TRUE == isProvider) {
				buyer1 = FinanceSessionContext.getEnterpriseName();
				if (enterpriseId == null) {
					if (FinanceSessionContext.isEnterprise()) {
						enterpriseId = FinanceSessionContext.getEnterpriseId();
					}
				}
			} else {
				if (enterpriseId == null) {
					if (FinanceSessionContext.isEnterprise()) {
						enterpriseId = FinanceSessionContext.getEnterpriseId();
					}
				}
			}
		}

		PageList<PickupApplicationWarehouseEntity> pages = pickupApplicationWarehouseService.inquirePickupApplicationWarehousePageList(pickupStates, pickupIds, enterpriseId, pickupNumber, creator, screatDt, ecreatDt, buyer, buyer1, spickupDt, epickupDt, creatorId, page);
		PageList<PickupApplicationWarehouseDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (PickupApplicationWarehouseEntity pawe : pages) {
			PickupApplicationWarehouseDetail pawd = new PickupApplicationWarehouseDetail();
			BeanUtils.copyProperties(pawe, pawd);
			pawd.setInvoiceType(pawe.getInvoiceType().ordinal());
			pawd.setProductType(pawe.getProductType().ordinal());
			pawd.setPickupState(pawe.getPickupState().ordinal());

			if (null != pawe.getPickupState1()) {
				pawd.setPickupState1(pawe.getPickupState1().ordinal());
			}

			if (pawe.getCreatorId().longValue() == FinanceSessionContext.getAccountId().longValue() && FinanceSessionContext.getAccountFullName().equals(pawe.getUpdator())) {
				pawd.setSelf(Boolean.TRUE);
			}

			pawd.setPickupStateView(pawe.getPickupState().getValue());

			//提货货物
			List<PickupBulkstockWarehouseEntity> pbwes = pickupBulkstockWarehouseService.inquirePickupBulkstockWarehouseList(pawe.getPickupId(), null);
			for (PickupBulkstockWarehouseEntity pbwe : pbwes) {
				PickupBulkstockWarehouseDetail pbwd = new PickupBulkstockWarehouseDetail();
				BeanUtils.copyProperties(pbwe, pbwd);
				FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(pbwe.getFinanceId());
				pbwd.setProductType(finance.getProductType().ordinal());

				BulkstockInfoEntity bie = bulkstockInfoService.inquireBulkstockInfo(pbwe.getBulkstockInfoId());
				pbwd.setSpecifician(bie.getSpecificationName());
				
				//查询监管量
				StringBuffer sql = new StringBuffer("SELECT * FROM view_fin_pickupable_bulkstock v WHERE v.ENTERPRISE_ID = ").append(pawe.getEnterpriseId());
				sql.append(" AND v.BULKSTOCK_INFO_ID = ").append(pbwe.getBulkstockInfoId());
				sql.append(" AND v.WAREHOUSE_ID = ").append("'"+pbwe.getWarehouseId()+"'");
				Session session = SessionRepository.getCurrentSession();
				List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("WEIGHT").addScalar("LOCATION_ID").addScalar("BULKSTOCK_NAME").addScalar("PRODUCT_TYPE").addScalar("BULKSTOCK_INFO_ID").addScalar("WAREHOUSE_NAME").addScalar("LOCATION_NAME").addScalar("LOCATION_AREA").addScalar("SPECIFICATION").list();
				List<PickupBulkstockInfo> list = new ArrayList<>();
				for (Object l : datas) {
					Object[] os = (Object[])l;
					if (BigDecimal.ZERO.compareTo((BigDecimal) os[0]) >= 0) {
						continue;
					}
					pbwd.setSupervisionQuantity((BigDecimal) os[0]);
				}
				SessionRepository.closeCurrentSession();

				pawd.getBulkstockList().add(pbwd);
			}

			results.add(pawd);
		}
		return results;
	}

	@Override
	public PageList<PickupApplicationWarehouseDetail> inquireFinancePickupApplicationWarehousePageList1(
			Integer[] pickupState, String pickupNumber, String creator, Date screatDt, Date ecreatDt, Long enterpriseId,
			String buyer, Date spickupDt, Date epickupDt, String financeNumber, Integer productType, Boolean isProvider,
			String bulkstockName, Long financeId, String warehouseName, PageCriteria page) {
		Long creatorId = null;

		List<WarePickupStateEnum> pickupStates = null;
		if (pickupState != null && pickupState.length > 0) {
			pickupStates = new ArrayList<>();
			for (int i = 0; i < pickupState.length; i++) {
				if (pickupState[i] != null) {
					pickupStates.add(WarePickupStateEnum.valueOf(pickupState[i]));
				}
			}
		}

		List<Long> pickupIds = null;
		if (StringUtil.isNotBlank(financeNumber) || productType != null) {
			pickupIds = pickupBulkstockWarehouseService.getPickupIds(financeNumber, productType, bulkstockName, financeId, warehouseName);
		}
		if (pickupIds != null && pickupIds.size() == 0) {
			return new PageList<>(page);
		}
		logger.info("=------------------"+pickupIds);
		String buyer1=null;
		if(financeId == null){
			if (Boolean.TRUE == isProvider) {
				buyer1 = FinanceSessionContext.getEnterpriseName();
			} else {
				if (enterpriseId == null) {
					if (FinanceSessionContext.isEnterprise()) {
						enterpriseId = FinanceSessionContext.getEnterpriseId();
					}
				}
			}
		}

		PageList<PickupApplicationWarehouseEntity> pages = pickupApplicationWarehouseService.inquirePickupApplicationWarehousePageList(pickupStates, pickupIds, enterpriseId, pickupNumber, creator, screatDt, ecreatDt, buyer, buyer1, spickupDt, epickupDt, creatorId, page);
		PageList<PickupApplicationWarehouseDetail> results = new PageList<>(page, pages.getTotalRecordCount());
		for (PickupApplicationWarehouseEntity pawe : pages) {
			PickupApplicationWarehouseDetail pawd = new PickupApplicationWarehouseDetail();
			BeanUtils.copyProperties(pawe, pawd);
			logger.info("======================================pickupId:" + pawe.getPickupId() + "pickupState:" + pawe.getPickupState());
			pawd.setInvoiceType(pawe.getInvoiceType().ordinal());
			pawd.setProductType(pawe.getProductType().ordinal());
			pawd.setPickupState(pawe.getPickupState().ordinal());

			if (null != pawe.getPickupState1()) {
				pawd.setPickupState1(pawe.getPickupState1().ordinal());
			}

			if (pawe.getCreatorId().longValue() == FinanceSessionContext.getAccountId().longValue() && FinanceSessionContext.getAccountFullName().equals(pawe.getUpdator())) {
				pawd.setSelf(Boolean.TRUE);
			}

			pawd.setPickupStateView(pawe.getPickupState().getValue());

			List<FinanceFilesInfoEntity> ffies = financeFilesInfoService.inquireFinanceFilesInfoListByPickupId(pawe.getPickupId());
			List<FinanceFilesInfoDetail> ffids = new ArrayList<>();
			for (FinanceFilesInfoEntity ffie : ffies) {
				FinanceFilesInfoDetail ffid = new FinanceFilesInfoDetail();
				BeanUtils.copyProperties(ffie, ffid);
				StringBuffer sb = new StringBuffer();
				StringBuffer sb1 = new StringBuffer();
				StringBuffer sb2 = new StringBuffer();
				for (String s : ffie.getFilesUuid().split(",")) {
					SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(s);
					if (sfie == null) {
						continue;
					}
					sb2.append(sfie.getFilesSign() + ",");
					sb1.append(sfie.getMsg() + ",");
					sb.append(sfie.getFileSignState().ordinal() + ",");
				}
				if (sb != null && sb.length() > 0) {
					sb = sb.deleteCharAt(sb.length() - 1);
					sb1 = sb1.deleteCharAt(sb1.length() - 1);
					sb2 = sb2.deleteCharAt(sb2.length() - 1);
				}
				ffid.setFileSignState(sb.toString());
				ffid.setMsg(sb1.toString());
				ffid.setIsSign(sb2.toString());
				ffids.add(ffid);
			}
			pawd.setFinanceFilesInfoList(ffids);

			List<PickupBulkstockWarehouseEntity> pbwes = pickupBulkstockWarehouseService.inquirePickupBulkstockWarehouseList(pawe.getPickupId(), financeId);
			for (PickupBulkstockWarehouseEntity pbwe : pbwes) {
				PickupBulkstockWarehouseDetail pbwd = new PickupBulkstockWarehouseDetail();
				BeanUtils.copyProperties(pbwe, pbwd);
				pbwd.setProductType(pbwe.getProductType().ordinal());

				StringBuffer sql = new StringBuffer();
				sql.append("SELECT (T1.WEIGHT - IFNULL(T2.PICKUP_QUANTITY, 0)) as WEIGHT, T1.LOCATION_ID as LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, T1.FINANCE_ID AS FINANCE_ID, T1.FINANCE_NUMBER AS FINANCE_NUMBER, T1.APPLICATION_DT AS APPLICATION_DT, T1.LOCATION_AREA AS LOCATION_AREA, T1.LOCATION_NAME AS LOCATION_NAME FROM (SELECT SUM(WEIGHT) AS WEIGHT, LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, c.PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, a.FINANCE_ID AS FINANCE_ID, a.FINANCE_NUMBER AS FINANCE_NUMBER, c.APPLICATION_DT AS APPLICATION_DT, a.LOCATION_AREA AS LOCATION_AREA, a.LOCATION_NAME AS LOCATION_NAME FROM fin_container_inventory a, fin_container_bulkstock b, fin_finance_application c WHERE a.INVENTORY_ID = b.INVENTORY_ID");
				sql.append(" AND a.LOCATION_ID ='").append(pbwe.getLocationId() + "'");
				sql.append(" AND a.FINANCE_NUMBER ='").append(pbwe.getFinanceNumber() + "'");
				sql.append(" AND a.FINANCE_ID = c.FINANCE_ID AND c.FINANCE_STATE IN (7,9,25,26,27,28,29,30) GROUP BY a.FINANCE_ID, LOCATION_ID) T1 LEFT JOIN (SELECT SUM(PICKUP_QUANTITY) AS PICKUP_QUANTITY, LOCATION_ID, FINANCE_NUMBER FROM fin_pickup_bulkstock_warehouse d, FIN_PICKUP_APPLICATION_WAREHOUSE e where d.PICKUP_ID = e.PICKUP_ID AND e.PICKUP_STATE NOT IN(1, 13) GROUP BY FINANCE_NUMBER, LOCATION_ID) T2 ON T1.LOCATION_ID = T2.LOCATION_ID AND T1.FINANCE_NUMBER = T2.FINANCE_NUMBER WHERE T1.LOCATION_ID IS NOT NULL AND T1.LOCATION_ID <> '';");
				Session session = SessionRepository.getCurrentSession();

				List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("WEIGHT").addScalar("LOCATION_ID").addScalar("BULKSTOCK_NAME").addScalar("PRODUCT_TYPE").addScalar("BULKSTOCK_INFO_ID").addScalar("WAREHOUSE_NAME").addScalar("FINANCE_ID").addScalar("FINANCE_NUMBER").addScalar("LOCATION_NAME").addScalar("LOCATION_AREA").addScalar("APPLICATION_DT").addScalar("SPECIFICATION").list();
				for (Object l : datas) {
					Object[] os = (Object[])l;
					pbwd.setSupervisionQuantity((BigDecimal) os[0]);
					pbwd.setLocationName((String) os[8]);
					pbwd.setLocationArea((String) os[9]);
					pbwd.setFinanceApplicationDate((Date) os[10]);
					pbwd.setSpecifician((String) os[11]);
				}

				pawd.getBulkstockList().add(pbwd);
				SessionRepository.closeCurrentSession();
			}

			results.add(pawd);
		}
		return results;
	}

	@Override
	@Transactional
	public PickupApplicationWarehouseDetail preservationBussinessAuditOpinion(Long pickupId, Boolean auditState, String auditRemark) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		if(pawe.getSubmissionStatus() == Boolean.TRUE){
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		pawe.setAuditState(auditState);
		pawe.setAuditRemark(auditRemark);

		pawe.setAuditDate(DateUtil.formatDatetime(new Date()));
		pawe.setAuditorId(FinanceSessionContext.getAccountId());
		pawe.setAuditor(FinanceSessionContext.getAccountFullName());

		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		PickupApplicationWarehouseDetail pawd = new PickupApplicationWarehouseDetail();
		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor(pawe.getAuditor());
		pawd.setAuditDate(pawe.getAuditDate());
		pawd.setAuditState(pawe.getAuditState());

		pawd.setSubmissionStatus(pawe.getSubmissionStatus());
		return pawd;
	}

	@Override
	@Transactional
	public PickupApplicationWarehouseDetail submitBussinessAuditOpinions(Long pickupId, Boolean auditState, String auditRemark) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		preservationBussinessAuditOpinion(pickupId, auditState, auditRemark);
		if (Boolean.FALSE == auditState) {
			initWarehousePickup(pickupId);
			pawe.setPickupState(WarePickupStateEnum.REJECT);
			pawe.setFinalId(null);
			pawe.setFinalNode("");

			List<PickupBulkstockWarehouseEntity> pbwes = pickupBulkstockWarehouseService.inquirePickupBulkstockWarehouseList(pickupId, null);
			for (PickupBulkstockWarehouseEntity pbwe : pbwes) {
				FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(pbwe.getFinanceId());
				//				finance.setFinanceState(FinanceStateEnum.PICKUP_APPROVE_WAREHOUSE_REJECT);
				financeApplicationService.updateFinanceApplication(finance);
			}
		} else {
			pawe.setSubmissionStatus(Boolean.TRUE);
			pawe.setCallback(Boolean.FALSE);
			pawe.setFinalId(ApiFinanceStateEnum.YY.getCode());
			pawe.setFinalNode(ApiFinanceStateEnum.YY.getView());
			//消息推送-运营部
			SendLetterMessage.sendLetterMessage("warehouseAudit3_1", String.format(tmp, pawe.getEnterpriseName(), pawe.getPickupNumber(), "运营部"));
		}
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);

		FinanceAuditLogEntity fale=new FinanceAuditLogEntity();
		fale.setAuditDate(DateUtil.now());
		fale.setRoleName(sb.toString());
		if(auditState == false){
			fale.setAuditState(0L);
		}else{
			fale.setAuditState(1L);
		}

		fale.setOpinion("商务部:" + auditRemark);
		fale.setAuditJoinId(pickupId);//审核关联业务ID  如:融资ID、放款ID、提货ID
		fale.setAuditTask(7L);//1:融资、2:放款、3:提货  、4：用户审核 、5:用户等级审核、 6：临时额度审核 7：代采代销提货
		fale.setAccountId(FinanceSessionContext.getAccountId());//当前审批用户信息
		financeAuditLogService.createFinanceAuditLogEntity(fale);

		PickupApplicationWarehouseDetail pawd=new PickupApplicationWarehouseDetail();
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor(pawe.getAuditor());
		pawd.setAuditDate(pawe.getAuditDate());
		pawd.setAuditState(pawe.getAuditState());
		pawd.setSubmissionStatus(pawe.getSubmissionStatus());
		return pawd;
	}

	@Override
	@Transactional
	public PickupApplicationWarehouseDetail preservationLeaderBussinessAuditOpinion(Long pickupId, Boolean auditState2, String auditRemark2) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		pawe.setAuditState2(auditState2);
		pawe.setAuditRemark2(auditRemark2);
		pawe.setAuditDate2(DateUtil.formatDatetime(new Date()));
		pawe.setAuditorId2(FinanceSessionContext.getAccountId());
		pawe.setAuditor2(FinanceSessionContext.getAccountFullName());

		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		PickupApplicationWarehouseDetail pawd = new PickupApplicationWarehouseDetail();
		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor2(pawe.getAuditor2());
		pawd.setAuditDate2(pawe.getAuditDate2());
		pawd.setAuditState2(pawe.getAuditState2());
		pawd.setSubmissionStatus2(pawe.getSubmissionStatus2());
		return pawd;
	}

	@Override
	@Transactional
	public PickupApplicationWarehouseDetail submitLeaderBussinessAuditOpinion(Long pickupId, Boolean auditState2, String auditRemark2) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		preservationLeaderBussinessAuditOpinion(pickupId, auditState2, auditRemark2);
		if (Boolean.FALSE == auditState2) {
			initWarehousePickup(pickupId);
		} else {
			pawe.setFinalId(ApiFinanceStateEnum.YY.getCode());
			pawe.setFinalNode(ApiFinanceStateEnum.YY.getView());
			pawe.setSubmissionStatus2(Boolean.TRUE);
		}
		FinanceAuditLogEntity fale=new FinanceAuditLogEntity();
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		fale.setAuditDate(DateUtil.now());
		fale.setRoleName(sb.toString());
		if(auditState2 == false){
			fale.setAuditState(0L);
		}else{
			fale.setAuditState(1L);
		}
		fale.setOpinion("商务部领导:" + auditRemark2);
		fale.setAuditJoinId(pickupId);//审核关联业务ID  如:融资ID、放款ID、提货ID
		fale.setAuditTask(7L);//1:融资、2:放款、3:提货  、4：用户审核 、5:用户等级审核、 6：临时额度审核 7：代采代销提货
		fale.setCreateDateTime(DateUtil.now());
		fale.setAccountId(FinanceSessionContext.getAccountId());//当前审批用户信息
		financeAuditLogService.createFinanceAuditLogEntity(fale);

		PickupApplicationWarehouseDetail pawd=new PickupApplicationWarehouseDetail();
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor2(pawe.getAuditor2());
		pawd.setAuditDate2(pawe.getAuditDate2());
		pawd.setAuditState2(pawe.getAuditState2());
		pawd.setSubmissionStatus2(pawe.getSubmissionStatus2());
		return pawd;
	}

	@Override
	@Transactional
	public PickupApplicationWarehouseDetail preservationOperateBussinessAuditOpinion(Long pickupId, Boolean auditState3, String auditRemark3) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		pawe.setAuditState3(auditState3);
		pawe.setAuditRemark3(auditRemark3);
		pawe.setAuditDate3(DateUtil.formatDatetime(new Date()));
		pawe.setAuditorId3(FinanceSessionContext.getAccountId());
		pawe.setAuditor3(FinanceSessionContext.getAccountFullName());

		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		PickupApplicationWarehouseDetail pawd=new PickupApplicationWarehouseDetail();
		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor3(pawe.getAuditor3());
		pawd.setAuditDate3(pawe.getAuditDate3());
		pawd.setAuditState3(pawe.getAuditState3());
		pawd.setSubmissionStatus3(pawe.getSubmissionStatus3());
		return pawd;
	}

	@Override
	@Transactional
	public PickupApplicationWarehouseDetail submitOperateBussinessAuditOpinion(Long pickupId, Boolean auditState3, String auditRemark3) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		preservationOperateBussinessAuditOpinion(pickupId, auditState3, auditRemark3);
		if (Boolean.FALSE == auditState3) {
			initWarehousePickup(pickupId);
		} else {

			List<FinanceFilesInfoEntity> ffies = financeFilesInfoService.inquireFinanceFilesInfoListByPickupId(pickupId);

			pawe.setFinalId(ApiFinanceStateEnum.CSWC.getCode());
			pawe.setFinalNode(ApiFinanceStateEnum.CSWC.getView());
			pawe.setSubmissionStatus3(Boolean.TRUE);

			if (ffies != null && ffies.size() > 0) {
				for (FinanceFilesInfoEntity ffie : ffies) {
					for (String s : ffie.getFilesUuid().split(",")) {
						SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(s);
						sfie.setFileSignState(FileSignStateEnum.UNKNOWN);
						signFileInfoService.updateSignFileInfo(sfie);
					}
				}
				pawe.setPickupState(WarePickupStateEnum.WAIT_CONTRACT_SUBMIT);
			} else {
				pawe.setPickupState(WarePickupStateEnum.WAIT_CONTRACT_UPLOAD);
			}

			//消息推送-合同上传
			SendLetterMessage.sendLetterMessage("warehousePickApplicationUpload_1", String.format(tmp, pawe.getEnterpriseName(), pawe.getPickupNumber(), "合同上传"));
		}
		FinanceAuditLogEntity fale=new FinanceAuditLogEntity();
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);

		fale.setAuditDate(DateUtil.now());
		fale.setRoleName(sb.toString());
		if(auditState3 == false){
			fale.setAuditState(0L);
		}else{
			fale.setAuditState(1L);
		}
		fale.setOpinion("运营部:" + auditRemark3);
		fale.setAuditJoinId(pickupId);//审核关联业务ID  如:融资ID、放款ID、提货ID
		fale.setAuditTask(7L);//1:融资、2:放款、3:提货  、4：用户审核 、5:用户等级审核、 6：临时额度审核 7：代采代销提货
		fale.setCreateDateTime(DateUtil.now());
		fale.setAccountId(FinanceSessionContext.getAccountId());//当前审批用户信息
		financeAuditLogService.createFinanceAuditLogEntity(fale);

		PickupApplicationWarehouseDetail pawd=new PickupApplicationWarehouseDetail();
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor3(pawe.getAuditor());
		pawd.setAuditDate3(pawe.getAuditDate());
		pawd.setAuditState3(pawe.getAuditState3());
		pawd.setSubmissionStatus3(pawe.getSubmissionStatus3());

		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		return pawd;
	}

	/** 风控审核*/
	@Override
	@Transactional
	public PickupApplicationWarehouseDetail preservationRiskBussinessAuditOpinion(Long pickupId, Boolean auditState4, String auditRemark4) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);

		if(pawe.getSubmissionStatus4() == Boolean.TRUE){
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}

		pawe.setAuditState4(auditState4);
		pawe.setAuditRemark4(auditRemark4);
		pawe.setAuditDate4(DateUtil.formatDatetime(new Date()));
		pawe.setAuditorId4(FinanceSessionContext.getAccountId());
		pawe.setAuditor4(FinanceSessionContext.getAccountFullName());

		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		PickupApplicationWarehouseDetail pawd = new PickupApplicationWarehouseDetail();
		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor4(pawe.getAuditor4());
		pawd.setAuditDate4(pawe.getAuditDate4());
		pawd.setAuditState4(pawe.getAuditState4());
		pawd.setSubmissionStatus4(pawe.getSubmissionStatus4());
		return pawd;
	}

	@Override
	@Transactional
	public PickupApplicationWarehouseDetail submitRiskBussinessAuditOpinion(Long pickupId, Boolean auditState4, String auditRemark4) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		preservationRiskBussinessAuditOpinion(pickupId, auditState4, auditRemark4);
		if (Boolean.FALSE == auditState4) {
			initWarehousePickup(pickupId);
		} else {
			pawe.setFinalId(ApiFinanceStateEnum.ZJ.getCode());
			pawe.setFinalNode(ApiFinanceStateEnum.ZJ.getView());
			pawe.setSubmissionStatus4(Boolean.TRUE);

			//消息推送-资金
			SendLetterMessage.sendLetterMessage("warehouseAudit6_1", String.format(tmp, pawe.getEnterpriseName(), pawe.getPickupNumber(), "资金部"));
		}
		FinanceAuditLogEntity fale=new FinanceAuditLogEntity();
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);

		fale.setAuditDate(DateUtil.now());
		fale.setRoleName(sb.toString());
		if(auditState4 == false){
			fale.setAuditState(0L);
		}else{
			fale.setAuditState(1L);
		}
		fale.setOpinion("风控部:" + auditRemark4);
		fale.setAuditJoinId(pickupId);//审核关联业务ID  如:融资ID、放款ID、提货ID
		fale.setAuditTask(7L);//1:融资、2:放款、3:提货  、4：用户审核 、5:用户等级审核、 6：临时额度审核 7：代采代销提货
		fale.setFinalState(pawe.getFinalId());
		fale.setCreateDateTime(DateUtil.now());
		fale.setAccountId(FinanceSessionContext.getAccountId());//当前审批用户信息
		financeAuditLogService.createFinanceAuditLogEntity(fale);

		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		PickupApplicationWarehouseDetail pawd=new PickupApplicationWarehouseDetail();
		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor4(pawe.getAuditor4());
		pawd.setAuditDate4(pawe.getAuditDate4());
		pawd.setAuditState4(pawe.getAuditState4());
		pawd.setSubmissionStatus4(pawe.getSubmissionStatus4());

		return pawd;
	}

	//风控领导审核
	@Override
	@Transactional
	public PickupApplicationWarehouseDetail preservationRiskAdminBussinessAuditOpinion(Long pickupId, Boolean auditState5, String auditRemark5) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		if(pawe.getSubmissionStatus5() == Boolean.TRUE){
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		pawe.setAuditState5(auditState5);
		pawe.setAuditRemark5(auditRemark5);
		pawe.setAuditDate5(DateUtil.formatDatetime(new Date()));
		pawe.setAuditorId5(FinanceSessionContext.getAccountId());
		pawe.setAuditor5(FinanceSessionContext.getAccountFullName());
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
		PickupApplicationWarehouseDetail pawd=new PickupApplicationWarehouseDetail();
		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor5(pawe.getAuditor5());
		pawd.setAuditDate5(pawe.getAuditDate5());
		pawd.setAuditState5(pawe.getAuditState5());
		pawd.setSubmissionStatus5(pawe.getSubmissionStatus5());
		return pawd;
	}

	@Override
	@Transactional
	public PickupApplicationWarehouseDetail submitRiskAdminBussinessAuditOpinion(Long pickupId, Boolean auditState5, String auditRemark5) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		preservationRiskAdminBussinessAuditOpinion(pickupId, auditState5, auditRemark5);
		if (Boolean.FALSE == auditState5) {
			initWarehousePickup(pickupId);
		} else {
			pawe.setFinalId(ApiFinanceStateEnum.ZJ.getCode());
			pawe.setFinalNode(ApiFinanceStateEnum.ZJ.getView());
			pawe.setSubmissionStatus5(Boolean.TRUE);
		}
		FinanceAuditLogEntity fale=new FinanceAuditLogEntity();
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);

		fale.setAuditDate(DateUtil.now());
		fale.setRoleName(sb.toString());
		if(auditState5 == false){
			fale.setAuditState(0L);
		}else{
			fale.setAuditState(1L);
		}
		fale.setOpinion("风控领导:" + auditRemark5);
		fale.setAuditJoinId(pickupId);//审核关联业务ID  如:融资ID、放款ID、提货ID
		fale.setAuditTask(7L);//1:融资、2:放款、3:提货  、4：用户审核 、5:用户等级审核、 6：临时额度审核 7：代采代销提货
		fale.setCreateDateTime(DateUtil.now());
		fale.setAccountId(FinanceSessionContext.getAccountId());//当前审批用户信息
		financeAuditLogService.createFinanceAuditLogEntity(fale);

		PickupApplicationWarehouseDetail pawd=new PickupApplicationWarehouseDetail();
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor5(pawe.getAuditor5());
		pawd.setAuditDate5(pawe.getAuditDate5());
		pawd.setAuditState5(pawe.getAuditState5());
		pawd.setSubmissionStatus5(pawe.getSubmissionStatus5());

		return pawd;
	}

	//财务审核
	@Override
	@Transactional
	public PickupApplicationWarehouseDetail preservationFinanceBussinessAuditOpinion(Long pickupId, Boolean auditState6, String auditRemark6) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		if(pawe.getSubmissionStatus6() == Boolean.TRUE){
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		pawe.setAuditState6(auditState6);
		pawe.setAuditRemark6(auditRemark6);
		pawe.setAuditDate6(DateUtil.formatDatetime(new Date()));
		pawe.setAuditorId6(FinanceSessionContext.getAccountId());
		pawe.setAuditor6(FinanceSessionContext.getAccountFullName());
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
		PickupApplicationWarehouseDetail pawd=new PickupApplicationWarehouseDetail();
		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor6(pawe.getAuditor6());
		pawd.setAuditDate6(pawe.getAuditDate6());
		pawd.setAuditState6(pawe.getAuditState6());
		pawd.setFilesUuid6(pawe.getFilesUuid6());
		pawd.setSubmissionStatus6(pawe.getSubmissionStatus6());
		return pawd;
	}

	@Override
	@Transactional
	public PickupApplicationWarehouseDetail submitFinanceBussinessAuditOpinion(Long pickupId, Boolean auditState6, String auditRemark6) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		preservationFinanceBussinessAuditOpinion(pickupId, auditState6, auditRemark6);
		if (Boolean.FALSE == auditState6) {
			initWarehousePickup(pickupId);
		} else {
			pawe.setFinalId(ApiFinanceStateEnum.ZJMANAGE.getCode());
			pawe.setFinalNode(ApiFinanceStateEnum.ZJMANAGE.getView());
			pawe.setSubmissionStatus6(Boolean.TRUE);

			//消息推送-资金领导
			SendLetterMessage.sendLetterMessage("warehouseAudit7_1", String.format(tmp, pawe.getEnterpriseName(), pawe.getPickupNumber(), "资金领导"));
		}
		FinanceAuditLogEntity fale=new FinanceAuditLogEntity();
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);

		fale.setAuditDate(DateUtil.now());
		fale.setRoleName(sb.toString());
		if(auditState6 == false){
			fale.setAuditState(0L);
		}else{
			fale.setAuditState(1L);
		}
		fale.setOpinion("财务部:" + auditRemark6);
		fale.setAuditJoinId(pickupId);//审核关联业务ID  如:融资ID、放款ID、提货ID
		fale.setAuditTask(7L);//1:融资、2:放款、3:提货  、4：用户审核 、5:用户等级审核、 6：临时额度审核 7：代采代销提货
		fale.setCreateDateTime(DateUtil.now());
		fale.setAccountId(FinanceSessionContext.getAccountId());//当前审批用户信息
		financeAuditLogService.createFinanceAuditLogEntity(fale);

		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
		PickupApplicationWarehouseDetail pawd=new PickupApplicationWarehouseDetail();

		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor6(pawe.getAuditor6());
		pawd.setAuditDate6(pawe.getAuditDate6());
		pawd.setAuditState6(pawe.getAuditState6());
		pawd.setFilesUuid6(pawe.getFilesUuid6());
		pawd.setSubmissionStatus6(pawe.getSubmissionStatus6());

		return pawd;
	}

	//财务审核
	@Override
	@Transactional
	public PickupApplicationWarehouseDetail preservationFinanceAdminBussinessAuditOpinion(Long pickupId, Boolean auditState7, String auditRemark7) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		if(pawe.getSubmissionStatus7() == Boolean.TRUE){
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		pawe.setAuditState7(auditState7);
		pawe.setAuditRemark7(auditRemark7);
		pawe.setAuditDate7(DateUtil.formatDatetime(new Date()));
		pawe.setAuditorId7(FinanceSessionContext.getAccountId());
		pawe.setAuditor7(FinanceSessionContext.getAccountFullName());
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
		PickupApplicationWarehouseDetail pawd=new PickupApplicationWarehouseDetail();
		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor7(pawe.getAuditor7());
		pawd.setAuditDate7(pawe.getAuditDate7());
		pawd.setAuditState7(pawe.getAuditState7());
		pawd.setSubmissionStatus7(pawe.getSubmissionStatus7());
		return pawd;
	}

	@Override
	@Transactional
	public PickupApplicationWarehouseDetail submitFinanceAdminBussinessAuditOpinion(Long pickupId, Boolean auditState7, String auditRemark7) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		preservationFinanceAdminBussinessAuditOpinion(pickupId, auditState7, auditRemark7);
		if (Boolean.FALSE == auditState7) {
			initWarehousePickup(pickupId);
		} else {
			pawe.setFinalId(ApiFinanceStateEnum.FMANAGE.getCode());
			pawe.setFinalNode(ApiFinanceStateEnum.FMANAGE.getView());
			pawe.setSubmissionStatus7(Boolean.TRUE);

			//消息推送-资金领导
			SendLetterMessage.sendLetterMessage("warehouseAudit8_1", String.format(tmp, pawe.getEnterpriseName(), pawe.getPickupNumber(), "副总经理"));
		}
		FinanceAuditLogEntity fale=new FinanceAuditLogEntity();
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);

		fale.setAuditDate(DateUtil.now());
		fale.setRoleName(sb.toString());
		if(auditState7 == false){
			fale.setAuditState(0L);
		}else{
			fale.setAuditState(1L);
		}
		fale.setOpinion("财务领导:" + auditRemark7);
		fale.setAuditJoinId(pickupId);//审核关联业务ID  如:融资ID、放款ID、提货ID
		fale.setAuditTask(7L);//1:融资、2:放款、3:提货  、4：用户审核 、5:用户等级审核、 6：临时额度审核 7：代采代销提货
		fale.setCreateDateTime(DateUtil.now());
		fale.setAccountId(FinanceSessionContext.getAccountId());//当前审批用户信息
		financeAuditLogService.createFinanceAuditLogEntity(fale);

		PickupApplicationWarehouseDetail pawd=new PickupApplicationWarehouseDetail();
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor7(pawe.getAuditor7());
		pawd.setAuditDate7(pawe.getAuditDate7());
		pawd.setAuditState7(pawe.getAuditState7());
		pawd.setSubmissionStatus7(pawe.getSubmissionStatus7());

		return pawd;
	}

	//副总经理审核
	@Override
	@Transactional
	public PickupApplicationWarehouseDetail preservationViceManagerBussinessAuditOpinion(Long pickupId, Boolean auditState8, String auditRemark8) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		if(pawe.getSubmissionStatus8() == Boolean.TRUE){
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		if (Boolean.FALSE == auditState8 && StringUtil.isBlank(auditRemark8)) {
			throw new BusinessException("请输入审核意见");
		} 
		pawe.setAuditState8(auditState8);
		pawe.setAuditRemark8(auditRemark8);
		pawe.setAuditDate8(DateUtil.formatDatetime(new Date()));
		pawe.setAuditorId8(FinanceSessionContext.getAccountId());
		pawe.setAuditor8(FinanceSessionContext.getAccountFullName());
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
		PickupApplicationWarehouseDetail pawd=new PickupApplicationWarehouseDetail();
		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor8(pawe.getAuditor8());
		pawd.setAuditDate8(pawe.getAuditDate8());
		pawd.setAuditState8(pawe.getAuditState8());
		pawd.setSubmissionStatus8(pawe.getSubmissionStatus8());
		return pawd;
	}

	@Override
	@Transactional
	public PickupApplicationWarehouseDetail submitViceManagerBussinessAuditOpinion(Long pickupId, Boolean auditState8, String auditRemark8) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		preservationViceManagerBussinessAuditOpinion(pickupId, auditState8, auditRemark8);
		if (Boolean.FALSE == auditState8) {
			initWarehousePickup(pickupId);
		} else {
			List<PickupBulkstockWarehouseEntity> pbwes = pickupBulkstockWarehouseService.inquirePickupBulkstockWarehouseList(pawe.getPickupId(), null);
			for (PickupBulkstockWarehouseEntity pbwe : pbwes) {
				FinanceMoneyStatementEntity valuetion = FinanceLoanCastor.fromWarehousePickupApplication(pbwe);
				FinanceMoneyStatementEntity interest = FinanceLoanCastor.fromWarehousePickupApplicationInterest(pbwe);
				FinanceMoneyStatementEntity others = FinanceLoanCastor.fromWarehousePickupApplicationOhers(pbwe);
				if (BigDecimal.ZERO.compareTo(valuetion.getAmount()) <= 0) {
					financeMoneyStatementService.createFinanceMoneyStatement(valuetion);
				}
				if (BigDecimal.ZERO.compareTo(interest.getAmount()) <= 0) {
					financeMoneyStatementService.createFinanceMoneyStatement(interest);
				}
				if (BigDecimal.ZERO.compareTo(others.getAmount()) < 0) {
					financeMoneyStatementService.createFinanceMoneyStatement(others);
				}
			}

			pawe.setFinalId(ApiFinanceStateEnum.FINISHED.getCode());
			pawe.setFinalNode(ApiFinanceStateEnum.FINISHED.getView());
			pawe.setSubmissionStatus8(Boolean.TRUE);

			List<FinanceFilesInfoEntity> ffies = financeFilesInfoService.inquireFinanceFilesInfoListByPickupId(pickupId);
			outer: for (FinanceFilesInfoEntity ffie : ffies) {
				for (String s : ffie.getFilesUuid().split(",")) {
					SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(s);
					if ("1".equals(sfie.getFilesSign())) {
						pawe.setPickupState1(WarePickupStateEnum.WAIT_PLATFORM_SIGN);
						break outer;
					} else {
						pawe.setPickupState1(WarePickupStateEnum.PLATFORM_SIGNED);
					}
				}
			}

			pawe.setPickupState(WarePickupStateEnum.WAIT_RELEASE);
			//消息推送-资金领导
			SendLetterMessage.sendLetterMessage("operateWarehousePickApplication_1", String.format(tmp, pawe.getEnterpriseName(), pawe.getPickupNumber(), "提货处理"));
		}
		FinanceAuditLogEntity fale=new FinanceAuditLogEntity();
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);

		fale.setAuditDate(DateUtil.now());
		fale.setRoleName(sb.toString());
		if(auditState8 == false){
			fale.setAuditState(0L);
		}else{
			fale.setAuditState(1L);
		}
		fale.setOpinion("副总经理:" + auditRemark8);
		fale.setAuditJoinId(pickupId);//审核关联业务ID  如:融资ID、放款ID、提货ID
		fale.setAuditTask(7L);//1:融资、2:放款、3:提货  、4：用户审核 、5:用户等级审核、 6：临时额度审核 7：代采代销提货
		fale.setCreateDateTime(DateUtil.now());
		fale.setAccountId(FinanceSessionContext.getAccountId());//当前审批用户信息
		financeAuditLogService.createFinanceAuditLogEntity(fale);

		PickupApplicationWarehouseDetail pawd = new PickupApplicationWarehouseDetail();

		PickupApplicationWarehouseDetail pawd1 = inquireFinancePickupApplicationWarehouse(pickupId);

		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor8(pawe.getAuditor());
		pawd.setAuditDate8(pawe.getAuditDate());
		pawd.setAuditState8(pawe.getAuditState8());
		pawd.setSubmissionStatus8(pawe.getSubmissionStatus8());

		FinanceCompleteResultEntity fcre = new FinanceCompleteResultEntity(pawe.getPickupId(), pawd1.getBulkstockList().get(0).getBulkstockName(), null, null, ApiTypeEnum.XSTH.getCode(), pawe.getPickupNumber(), DateUtil.now(), pawe.getEnterpriseName(), null, BigDecimal.ZERO);
		financeAuditLogService.createFinanceCompleteResultEntity(fcre);

		return pawd;
	}

	//总经理审核
	@Override
	@Transactional
	public PickupApplicationWarehouseDetail preservationManagerBussinessAuditOpinion(Long pickupId, Boolean auditState9, String auditRemark9) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		if(pawe.getSubmissionStatus9() == Boolean.TRUE){
			throw new BusinessException("审核意见已提交，不能再次修改！");
		}
		pawe.setAuditState9(auditState9);
		pawe.setAuditRemark9(auditRemark9);
		pawe.setAuditDate9(DateUtil.formatDatetime(new Date()));
		pawe.setAuditorId9(FinanceSessionContext.getAccountId());
		pawe.setAuditor9(FinanceSessionContext.getAccountFullName());
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
		PickupApplicationWarehouseDetail pawd=new PickupApplicationWarehouseDetail();
		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor9(pawe.getAuditor9());
		pawd.setAuditDate9(pawe.getAuditDate9());
		pawd.setAuditState9(pawe.getAuditState9());
		pawd.setSubmissionStatus9(pawe.getSubmissionStatus9());
		return pawd;
	}

	@Override
	@Transactional
	public PickupApplicationWarehouseDetail submitManagerBussinessAuditOpinion(Long pickupId, Boolean auditState9, String auditRemark9) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		preservationManagerBussinessAuditOpinion(pickupId, auditState9, auditRemark9);
		if (Boolean.FALSE == auditState9) {
			initWarehousePickup(pickupId);
		} else {
			List<PickupBulkstockWarehouseEntity> pbwes = pickupBulkstockWarehouseService.inquirePickupBulkstockWarehouseList(pawe.getPickupId(), null);
			for (PickupBulkstockWarehouseEntity pbwe : pbwes) {
				FinanceMoneyStatementEntity valuetion = FinanceLoanCastor.fromWarehousePickupApplication(pbwe);
				FinanceMoneyStatementEntity interest = FinanceLoanCastor.fromWarehousePickupApplicationInterest(pbwe);
				FinanceMoneyStatementEntity others = FinanceLoanCastor.fromWarehousePickupApplicationOhers(pbwe);
				if (BigDecimal.ZERO.compareTo(valuetion.getAmount()) <= 0) {
					financeMoneyStatementService.createFinanceMoneyStatement(valuetion);
				}
				if (BigDecimal.ZERO.compareTo(interest.getAmount()) <= 0) {
					financeMoneyStatementService.createFinanceMoneyStatement(interest);
				}
				if (BigDecimal.ZERO.compareTo(others.getAmount()) < 0) {
					financeMoneyStatementService.createFinanceMoneyStatement(others);
				}
			}

			pawe.setFinalId(ApiFinanceStateEnum.FINISHED.getCode());
			pawe.setFinalNode(ApiFinanceStateEnum.FINISHED.getView());
			pawe.setSubmissionStatus9(Boolean.TRUE);
			pawe.setPickupState(WarePickupStateEnum.WAIT_RELEASE);
		}
		FinanceAuditLogEntity fale=new FinanceAuditLogEntity();
		List<RoleListDto> rl = permissionAction.inquireAccountRoleList(FinanceSessionContext.getAccountId());
		StringBuffer sb = new StringBuffer();
		for (RoleListDto rlt : rl) {
			sb.append(rlt.getRoleName()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);

		fale.setAuditDate(DateUtil.now());
		fale.setRoleName(sb.toString());
		if(auditState9 == false){
			long audit1=0;
			fale.setAuditState(audit1);
		}else{
			long audit2=1;
			fale.setAuditState(audit2);
		}
		fale.setOpinion("总经理:" + auditRemark9);
		fale.setAuditJoinId(pickupId);//审核关联业务ID  如:融资ID、放款ID、提货ID
		fale.setAuditTask(7L);//1:融资、2:放款、3:提货  、4：用户审核 、5:用户等级审核、 6：临时额度审核 7：代采代销提货
		fale.setCreateDateTime(DateUtil.now());
		fale.setAccountId(FinanceSessionContext.getAccountId());//当前审批用户信息
		financeAuditLogService.createFinanceAuditLogEntity(fale);

		PickupApplicationWarehouseDetail pawd = new PickupApplicationWarehouseDetail();

		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		BeanUtils.copyProperties(pawe, pawd);
		pawd.setAuditor9(pawe.getAuditor());
		pawd.setAuditDate9(pawe.getAuditDate());
		pawd.setAuditState9(pawe.getAuditState9());
		pawd.setSubmissionStatus9(pawe.getSubmissionStatus9());

		return pawd;
	}

	private void initWarehousePickup(Long pickupId) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		pawe.setAuditState(Boolean.TRUE);
		pawe.setAuditRemark("");
		pawe.setSubmissionStatus(Boolean.FALSE);
		pawe.setAuditDate(null);
		pawe.setAuditorId(null);
		pawe.setAuditor("");

		pawe.setAuditState2(Boolean.TRUE);
		pawe.setAuditRemark2("");
		pawe.setSubmissionStatus2(Boolean.FALSE);
		pawe.setAuditDate2(null);
		pawe.setAuditorId2(null);
		pawe.setAuditor2("");

		pawe.setAuditState3(Boolean.TRUE);
		pawe.setAuditRemark3("");
		pawe.setSubmissionStatus3(Boolean.FALSE);
		pawe.setAuditDate3(null);
		pawe.setAuditorId3(null);
		pawe.setAuditor3("");

		pawe.setAuditState4(Boolean.TRUE);
		pawe.setAuditRemark4("");
		pawe.setSubmissionStatus4(Boolean.FALSE);
		pawe.setAuditDate4(null);
		pawe.setAuditorId4(null);
		pawe.setAuditor4("");

		pawe.setAuditState5(Boolean.TRUE);
		pawe.setAuditRemark5("");
		pawe.setSubmissionStatus5(Boolean.FALSE);
		pawe.setAuditDate5(null);
		pawe.setAuditorId5(null);
		pawe.setAuditor5("");

		pawe.setAuditState6(Boolean.TRUE);
		pawe.setAuditRemark6("");
		pawe.setSubmissionStatus6(Boolean.FALSE);
		pawe.setAuditDate6(null);
		pawe.setAuditorId6(null);
		pawe.setAuditor6("");

		pawe.setAuditState7(Boolean.TRUE);
		pawe.setAuditRemark7("");
		pawe.setSubmissionStatus7(Boolean.FALSE);
		pawe.setAuditDate7(null);
		pawe.setAuditorId7(null);
		pawe.setAuditor7("");

		pawe.setAuditState8(Boolean.TRUE);
		pawe.setAuditRemark8("");
		pawe.setSubmissionStatus8(Boolean.FALSE);
		pawe.setAuditDate8(null);
		pawe.setAuditorId8(null);
		pawe.setAuditor8("");

		pawe.setAuditState9(Boolean.TRUE);
		pawe.setAuditRemark9("");
		pawe.setSubmissionStatus9(Boolean.FALSE);
		pawe.setAuditDate9(null);
		pawe.setAuditorId9(null);
		pawe.setAuditor9("");

		pawe.setCallback(Boolean.TRUE);
		pawe.setPickupState(WarePickupStateEnum.FIRST_APPROVE);

		pawe.setFinalId(ApiFinanceStateEnum.SW.getCode());
		pawe.setFinalNode(ApiFinanceStateEnum.SW.getView());
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);

		//消息推送-商务部
		SendLetterMessage.sendLetterMessage("warehouseAudit1_1", String.format(tmp, pawe.getEnterpriseName(), pawe.getPickupNumber(), "商务部"));
	}

	@Override
	@Transactional
	public void createWarehousePickupContract(Long pickupId, String contractNumber, String contractDate, String send,
			String recieve, Long[] normId, String[] filesUuid, String[] filesSign,
			String[] isSign) {

		for (int i = 0; i < normId.length; i++) {
			if (StringUtil.isBlank(filesUuid[i])) {
				continue;
			}
			FinanceFilesNormEntity ffne = financeFilesNormService.inquireFinanceFilesNormDetail(normId[i]);
			FinanceFilesInfoEntity ffie = new FinanceFilesInfoEntity();
			ffie.setFilesUuid(filesUuid[i]);
			ffie.setPickupId(pickupId);
			ffie.setIsNotNull(ffne.getIsNotNull());
			ffie.setIsSign(ffne.getIsSign());
			ffie.setNormFileName(ffne.getNormFileName());
			ffie.setNormId(ffne.getNormId());
			financeFilesInfoService.createFinanceFilesInfo(ffie);

			String[] filesSigns = filesSign[i].split(",");
			String[] filesUuids = filesUuid[i].split(",");
			for (int j = 0; j< filesUuids.length; j++) {
				SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(filesUuids[j]);
				if (sfie == null) {
					sfie = new SignFileInfoEntity();
					sfie.setFileSignState(FileSignStateEnum.UNKNOWN);
					sfie.setFileUuid(filesUuids[j]);
					sfie.setUpdateDateTime(DateUtil.now());
					sfie.setFilesSign(filesSigns[j]);
					signFileInfoService.createSignFileInfo(sfie);
				}
			}
		}

		// 项目状态更新
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		pawe.setContractDate(contractDate);
		pawe.setContractNumber(contractNumber);
		pawe.setSend(send);
		pawe.setRecieve(recieve);
		pawe.setPickupState(WarePickupStateEnum.WAIT_CONTRACT_SUBMIT);
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
	}


	@Override
	@Transactional
	public void updateWarehousePickupContract(Long pickupId, String contractNumber, String contractDate, String send,
			String recieve, Long[] filesInfoId, String[] filesUuid, String[] filesSign,
			String[] isSign) {

		Boolean flag = Boolean.FALSE;

		for (int i = 0; i < filesInfoId.length; i++) {
			FinanceFilesInfoEntity ffie = financeFilesInfoService.inquireFinanceFilesInfo(filesInfoId[i]);
			ffie.setFilesUuid(filesUuid[i]);
			financeFilesInfoService.updateFinanceFilesInfo(ffie);

			String[] filesSigns = filesSign[i].split(",");
			String[] filesUuids = filesUuid[i].split(",");
			for (int j = 0; j< filesUuids.length; j++) {
				SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(filesUuids[j]);
				if (sfie == null) {
					sfie = new SignFileInfoEntity();
					sfie.setFileSignState(FileSignStateEnum.UNKNOWN);
					sfie.setFileUuid(filesUuids[j]);
					sfie.setUpdateDateTime(DateUtil.now());
					sfie.setFilesSign(filesSigns[j]);
					signFileInfoService.createSignFileInfo(sfie);
				} else {
					//					if (sfie.getFileSignState() == FileSignStateEnum.CALLBACK_ENTERPRISE || sfie.getFileSignState() == FileSignStateEnum.CALLBACK_PLATFORM) {
					//						flag = flag && Boolean.TRUE;
					//					}
					sfie.setFileUuid(filesUuids[j]);
					sfie.setUpdateDateTime(DateUtil.now());
					sfie.setFilesSign(filesSigns[j]);
					signFileInfoService.updateSignFileInfo(sfie);
				}
			}
		}

		// 项目状态更新
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		pawe.setContractDate(contractDate);
		pawe.setContractNumber(contractNumber);
		pawe.setSend(send);
		pawe.setRecieve(recieve);

		//		if (Boolean.TRUE == flag) {
		pawe.setPickupState(WarePickupStateEnum.WAIT_CONTRACT_SUBMIT);
		//		}
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
	}

	@Override
	@Transactional
	public void submitPickupContract(Long pickupId) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);
		pawe.setPickupState(WarePickupStateEnum.WAIT_CONFIRM);

		List<FinanceFilesInfoEntity> ffies = financeFilesInfoService.inquireFinanceFilesInfoListByPickupId(pickupId);
		for (FinanceFilesInfoEntity ffie : ffies) {
			if (StringUtil.isBlank(ffie.getFilesUuid())) {
				continue;
			}
			for (String f : ffie.getFilesUuid().split(",")) {
				SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(f);
				if (StringUtil.isNotBlank(sfie.getFilesSign()) && "1".equals(sfie.getFilesSign())) {
					pawe.setPickupState(WarePickupStateEnum.WAIT_CLIENT_SIGN);
					pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
					break;
				}
			}
		}

		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
	}

	@Override
	@Transactional
	public void callBackPickupContract(Long pickupId, String fileUuid, String remark) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);

		SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(fileUuid);
		if (FinanceSessionContext.isEnterprise()) {
			sfie.setFileSignState(FileSignStateEnum.CALLBACK_ENTERPRISE);
			sfie.setCallbackReamrk(sfie.getCallbackReamrk() + "发起人:"+FinanceSessionContext.getEnterpriseName() + "\t" + DateUtil.formatDatetime(DateUtils.now()) + "\n\r" + remark + "\n\r");
		} else {
			sfie.setFileSignState(FileSignStateEnum.CALLBACK_PLATFORM);
			sfie.setCallbackReamrk(sfie.getCallbackReamrk() + "发起人:"+FinanceSessionContext.getAccountFullName() + "\t" + DateUtil.formatDatetime(DateUtils.now()) + "\n\r" + remark + "\n\r");
		}
		signFileInfoService.updateSignFileInfo(sfie);

		//删除打回的签章记录
		List<SignFileSealInfoEntity> sfsies = signFileSealInfoService.inquireSignFileSealInfoList(fileUuid, null, null);
		for (SignFileSealInfoEntity sfsie : sfsies) {
			signFileSealInfoService.deleteSignFileSealInfo(sfsie.getSignFileSealId());
		}

		pawe.setPickupState(WarePickupStateEnum.CONTRACT_CALLBACK);
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
	}

	@Override
	@Transactional
	public void callBackPickupContractAll(Long pickupId, String remark) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);

		List<FinanceFilesInfoEntity> ffies = financeFilesInfoService.inquireFinanceFilesInfoListByPickupId(pickupId);
		for (FinanceFilesInfoEntity ffie : ffies) {
			for (String s : ffie.getFilesUuid().split(",")) {
				SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(s);
				if (sfie == null || sfie.getFileSignState() == FileSignStateEnum.CONFIRM) {
					continue;
				} else {
					if (FinanceSessionContext.isEnterprise()) {
						sfie.setFileSignState(FileSignStateEnum.CALLBACK_ENTERPRISE);
						sfie.setCallbackReamrk(sfie.getCallbackReamrk() + "发起人:"+FinanceSessionContext.getEnterpriseName() + "\t" + DateUtil.formatDatetime(DateUtils.now()) + "\n\r" + remark + "\n\r");
					} else {
						sfie.setFileSignState(FileSignStateEnum.CALLBACK_PLATFORM);
						sfie.setCallbackReamrk(sfie.getCallbackReamrk() + "发起人:"+FinanceSessionContext.getAccountFullName() + "\t" + DateUtil.formatDatetime(DateUtils.now()) + "\n\r" + remark + "\n\r");
					}
				}
				pawe.setPickupState(WarePickupStateEnum.CONTRACT_CALLBACK);
				pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
			}
		}
	}

	@Override
	@Transactional
	public void replacePickupContract(Long pickupId, String oldFileUuid, String newFileUuid, String remark) {
		FileEntry fe1 = transferService.inquireFileEntry(oldFileUuid);
		String filePath1 = ConfigPropertites.getProperties("UPLOAD_FILE_PATH") + fe1.getUri();

		//删除旧文件
		File oldFile = new File(filePath1);
		if (oldFile.exists() && oldFile.isFile()) {
			if (oldFile.delete()) {
				System.out.println("delete file:" + fe1.getFileName() + "successful!");
			} else {
				System.out.println("delete file:" + fe1.getFileName() + "failed!");
			}
		}
		//加入新文件

		FileEntry fe2 = transferService.inquireFileEntry(newFileUuid);
		String filePath2 = ConfigPropertites.getProperties("UPLOAD_FILE_PATH") + fe2.getUri();
		File newFile = new File(filePath2);
		copyFile(filePath2, oldFile.getParent() + "\\" + newFile.getName());

		BeanUtils.copyProperties(fe2, fe1, "fileUuid");
		PersistUtil.update(fe1);

		SignFileInfoEntity sfie = signFileInfoService.inquireSignFileInfo(oldFileUuid);
		sfie.setFileSignState(FileSignStateEnum.UNKNOWN);
		sfie.setUpdateReamark(sfie.getUpdateReamark() + "发起人:" + FinanceSessionContext.getAccountFullName() + "\t" + DateUtil.formatDatetime(DateUtils.now()) + "\n\r" + remark + "\n\r");
		signFileInfoService.updateSignFileInfo(sfie);

		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetail(pickupId);

		Boolean flag = Boolean.TRUE;

		List<FinanceFilesInfoEntity> ffies = financeFilesInfoService.inquireFinanceFilesInfoListByPickupId(pickupId);
		for (FinanceFilesInfoEntity ffie : ffies) {
			if (StringUtil.isBlank(ffie.getFilesUuid())) {
				continue;
			}
			for (String f : ffie.getFilesUuid().split(",")) {
				SignFileInfoEntity s = signFileInfoService.inquireSignFileInfo(f);
				if (s.getFileSignState() == FileSignStateEnum.CALLBACK_ENTERPRISE || s.getFileSignState() == FileSignStateEnum.CALLBACK_PLATFORM) {
					flag = flag && Boolean.FALSE;
				}
			}
		}

		if (Boolean.TRUE == flag) {
			pawe.setPickupState(WarePickupStateEnum.WAIT_CONTRACT_SUBMIT);
			pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
		}
	}

	private void copyFile(String oldPath, String newPath)  {    
		try  {    
			int byteread = 0;  
			File oldfile = new File(oldPath);  
			if (oldfile.exists()) {  //文件存在时
				InputStream inStream = new FileInputStream(oldPath);  //读入原文件   
				FileOutputStream fs = new FileOutputStream(newPath);    
				byte[] buffer = new byte[1024];    
				while ((byteread = inStream.read(buffer)) != -1) {  
					fs.write(buffer, 0, byteread);  
				}
				fs.close();
				inStream.close();    
			}    
		}
		catch  (Exception  e)  {    
			System.out.println("复制单个文件操作出错");    
			e.printStackTrace();    
		}    
	}

	@Override
	@Transactional
	public void syncInboundData() {
		ContainerInventoryService containerInventoryService = ComponentFactory.loadClass(ContainerInventoryService.class);
		FinanceApplicationActionApi financeApplicationActionApi = ComponentFactory.loadClass(FinanceApplicationActionApi.class);

		DetachedCriteria criteria = DetachedCriteria.forClass(ContainerInventoryEntity.class);
		criteria.add(Restrictions.eq("enabled", Boolean.TRUE));
		criteria.add(Restrictions.like("type", 1));
		List<ContainerInventoryEntity> cies = PersistUtil.get(criteria);
		for (ContainerInventoryEntity cie : cies) {
			Map<String, String> params = new HashMap<>();
			params.put("inboundNo", cie.getCaseNumber());
			String url = ConfigPropertites.getProperties("finance.syncLocationForInbound.service");
			String responseText = HttpClientHelper.post(url, params);
			logger.info("url:" + url);
			logger.info("params:" + params);
			logger.info("responseText:" + responseText);
			if (StringUtil.isBlank(responseText)) {
				continue;
			}
			ResultData result = JSON.toBean(responseText, ResultData.class);
			if ("success".equals(result.getStatus())) {
				try {
					cie.setLocationArea(result.getResult().getLocation_area());
					cie.setLocationId(result.getResult().getLocation_id());
					cie.setLocationName(result.getResult().getLocation_name());
					containerInventoryService.updateContainerInventory(cie);
					financeApplicationActionApi.lockWarehouseAndInbound(cie.getCaseNumber());
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
			}
		}
	}

	@Override
	public PageList<EnterpriseInvoiceInfo> inquireEnterpriseInvoiceInfoPageList(String invoiceEnterpriseName, PageCriteria page) {
		PageList<EnterpriseInvoiceInfoEntity> pages = enterpriseInvoiceInfoService.inquireEnterpriseInvoiceInfoPageList(FinanceSessionContext.getAccountId(), invoiceEnterpriseName, page);
		PageList<EnterpriseInvoiceInfo> results = new PageList<>(page, pages.getTotalRecordCount());
		for (EnterpriseInvoiceInfoEntity eiie : pages) {
			EnterpriseInvoiceInfo eii = new EnterpriseInvoiceInfo();
			BeanUtils.copyProperties(eiie, eii);
			results.add(eii);
		}
		return results;
	}

	@Override
	public EnterpriseInvoiceInfo inquireEnterpriseInvoiceInfo(String invoiceEnterpriseName) {
		EnterpriseInvoiceInfoEntity eiie = enterpriseInvoiceInfoService.inquireEnterpriseInvoiceInfo(FinanceSessionContext.getAccountId(), invoiceEnterpriseName);
		EnterpriseInvoiceInfo eii = new EnterpriseInvoiceInfo();
		BeanUtils.copyProperties(eiie, eii);
		return eii;
	}

	@Override
	public String inquireFinanceApplicationFinished(String financeNumber) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT (T1.WEIGHT - IFNULL(T2.PICKUP_QUANTITY, 0)) as WEIGHT, T1.LOCATION_ID as LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, T1.FINANCE_ID AS FINANCE_ID, T1.FINANCE_NUMBER AS FINANCE_NUMBER, T1.APPLICATION_DT AS APPLICATION_DT, T1.LOCATION_AREA AS LOCATION_AREA, T1.LOCATION_NAME AS LOCATION_NAME FROM (SELECT SUM(WEIGHT) AS WEIGHT, LOCATION_ID, BULKSTOCK_NAME, SPECIFICATION, c.PRODUCT_TYPE, BULKSTOCK_INFO_ID, WAREHOUSE_NAME, a.FINANCE_ID AS FINANCE_ID, a.FINANCE_NUMBER AS FINANCE_NUMBER, c.APPLICATION_DT AS APPLICATION_DT, a.LOCATION_AREA AS LOCATION_AREA, a.LOCATION_NAME AS LOCATION_NAME FROM fin_container_inventory a, fin_container_bulkstock b, fin_finance_application c WHERE a.INVENTORY_ID = b.INVENTORY_ID");
		sql.append(" AND a.FINANCE_NUMBER ='").append(financeNumber + "'");
		sql.append(" AND a.FINANCE_ID = c.FINANCE_ID AND ((c.FINANCE_STATE IN (9,25,26,27,28,29,30) AND (c.SETTLEMENT_METHOD = 1 OR ISNULL(c.SETTLEMENT_METHOD))) OR (c.FINANCE_STATE IN (7, 9, 25, 26, 27, 28, 29, 30) AND c.SETTLEMENT_METHOD = 2)) GROUP BY a.FINANCE_ID) T1 LEFT JOIN (SELECT SUM(PICKUP_QUANTITY) AS PICKUP_QUANTITY, LOCATION_ID, FINANCE_NUMBER FROM fin_pickup_bulkstock_warehouse d, FIN_PICKUP_APPLICATION_WAREHOUSE e where d.PICKUP_ID = e.PICKUP_ID AND e.PICKUP_STATE IN(11, 12) GROUP BY FINANCE_NUMBER, LOCATION_ID) T2 ON T1.LOCATION_ID = T2.LOCATION_ID AND T1.FINANCE_NUMBER = T2.FINANCE_NUMBER WHERE T1.LOCATION_ID IS NOT NULL AND T1.LOCATION_ID <> '';");
		Session session = SessionRepository.getCurrentSession();
		StringBuffer inboundNos = new StringBuffer("");

		List<Object> datas = session.createSQLQuery(sql.toString()).addScalar("WEIGHT").addScalar("LOCATION_ID").addScalar("BULKSTOCK_NAME").addScalar("PRODUCT_TYPE").addScalar("BULKSTOCK_INFO_ID").addScalar("WAREHOUSE_NAME").addScalar("FINANCE_ID").addScalar("FINANCE_NUMBER").addScalar("LOCATION_NAME").addScalar("LOCATION_AREA").addScalar("APPLICATION_DT").addScalar("SPECIFICATION").list();
		for (Object l : datas) {
			Object[] os = (Object[])l;
			FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(financeNumber);
			if (((BigDecimal) os[0]).compareTo(BigDecimal.ZERO) <= 0) {
				List<ContainerInventoryEntity> cies = containerInventoryService.inquireContainerInventoryList(finance.getFinanceId(), null);
				for (ContainerInventoryEntity cie : cies) {
					inboundNos = inboundNos.append(cie.getCaseNumber()).append(",");
				}
			} else {
				inboundNos = new StringBuffer("");
			}
		}
		if (inboundNos.length() > 0) {
			inboundNos.deleteCharAt(inboundNos.length() - 1);
		}
		SessionRepository.closeCurrentSession();
		return inboundNos.toString();
	}

	@Override
	@Transactional
	public void finishWarehousePickupApplication(String pickupNumber) {
		PickupApplicationWarehouseEntity pawe = pickupApplicationWarehouseService.inquirePickupApplicationWarehouseDetailByPickupNumber(pickupNumber);
		pawe.setPickupState(WarePickupStateEnum.RELEASED);
		pawe.setFinalNode("已完成");
		pickupApplicationWarehouseService.updatePickupApplicationWarehouse(pawe);
	}
}
